Package strings
implement simple functions to manipulate UTF-8 encoded strings.
Unlike JavaScript, strings are defined between double quotes “…”, not single quotes. Strings in Go are UTF-8
encoded by default. Due to UTF-8
encoding, Golang strings can contain a text which has characters from any language in the world.
To define an empty variable of string type, use the string
keyword. The following code demonstrates how to initialize a string.
package mainimport "fmt"func main() {var s string = "Hello, World"fmt.Printf(s)}
The len
function is used to find the length of a string. The len
function is made available in Go runtime; therefore, no packages need to be imported for this.
package mainimport "fmt"func main() {var s string = "Hello, World"fmt.Printf("%d",len(s))}
Golang strings are immutable, which means that they cannot be changed once they have been initialized. Changing these strings after initialization will cause the program to throw an error.
package mainimport "fmt"func main() {var s string = "Hello, World"// Uncomment the following line to change a value// in the string. A error will be thrown.// s[1] = 'c'fmt.Printf("%s",s)}
We can access individual elements in a Golang string using a for
loop (shown in the example below).
package mainimport "fmt"func main() {var s string = "Hello, World"for index, character := range(s){fmt.Printf("The character %c is in position %d \n", character, index)}}
We can also form a string from a slice of byte values using Golang strings.
package mainimport "fmt"func main() {myslice := []byte{0x48, 0x65, 0x6C, 0x6C, 0x6f}mystring := string(myslice)fmt.Printf(mystring)}
Further functions related to string operations can be found in the official documentation page.
Free Resources