0
0
GoConceptBeginner · 3 min read

What is string in Go: Explanation and Examples

In Go, a string is a sequence of bytes that represents text. It is immutable, meaning once created, it cannot be changed. Strings are used to store and manipulate text data in Go programs.
⚙️

How It Works

Think of a string in Go like a necklace made of beads, where each bead is a byte representing a character. This necklace is fixed in length and cannot be changed once made, which means you can't add or remove beads from it. If you want a different necklace, you create a new one.

Under the hood, Go stores strings as a sequence of bytes, often representing UTF-8 encoded text. This allows strings to hold any text, including letters, numbers, and symbols from many languages. Because strings are immutable, operations like adding or changing characters create new strings instead of modifying the original.

💻

Example

This example shows how to create a string and print it in Go.

go
package main

import "fmt"

func main() {
    var greeting string = "Hello, Go!"
    fmt.Println(greeting)
}
Output
Hello, Go!
🎯

When to Use

Use strings in Go whenever you need to work with text, such as names, messages, or any readable information. For example, strings are used to display text on the screen, read user input, or store data like URLs and file paths.

Because strings are immutable, they are safe to share across different parts of a program without worrying about accidental changes. When you need to build or modify text repeatedly, you can use types like strings.Builder for better performance.

Key Points

  • Strings in Go are sequences of bytes representing text.
  • They are immutable, so they cannot be changed after creation.
  • Strings usually hold UTF-8 encoded characters.
  • Use strings for any text data in your programs.
  • For efficient string building, use strings.Builder.

Key Takeaways

A string in Go is an immutable sequence of bytes representing text.
Strings store UTF-8 encoded characters, supporting many languages.
Use strings to handle any text data like messages, names, or URLs.
Modifying strings creates new strings; use strings.Builder for efficiency.
Strings are safe to share because they cannot be changed after creation.