Go String Data Type #
The string data type is used to store a sequence of characters (text).
String values must always be surrounded by double quotes ("
).
Declaring Strings in Go #
You can declare strings using either the var
keyword or the :=
shorthand.
package main
import ("fmt")
func main() {
var txt1 string = "Hello!" // typed declaration with initial value
var txt2 string // typed declaration without initial value
txt3 := "World 1" // untyped declaration with initial value
fmt.Printf("Type: %T, value: %v\n", txt1, txt1)
fmt.Printf("Type: %T, value: %v\n", txt2, txt2)
fmt.Printf("Type: %T, value: %v\n", txt3, txt3)
}
Result:
Type: string, value: Hello!
Type: string, value:
Type: string, value: World 1
Notes #
- A string without an initial value is set to the default empty string
""
. - Strings are immutable in Go, meaning their content cannot be changed after creation.
- Strings can be concatenated using the
+
operator.
Example of concatenation:
package main
import ("fmt")
func main() {
str1 := "Hello"
str2 := "World"
str3 := str1 + " " + str2
fmt.Println(str3)
}
Output:
Hello World