Strings

Another important built-in type is string. Assigning a string is as simple as:

  1. s := "Hello World!"

Strings in Go are a sequence of UTF-8 characters enclosed in double quotes (“).If you use the single quote (‘) you mean one character (encoded in UTF-8) —which is not a string in Go.

Once assigned to a variable, the string cannot be changed: strings in Go areimmutable. If you are coming from C, note that the following is not legal in Go:

  1. var s string = "hello"
  2. s[0] = 'c'

To do this in Go you will need the following:

  1. s := "hello"
  2. c := []rune(s) 1
  3. c[0] = 'c' 2
  4. s2 := string(c) 3
  5. fmt.Printf("%s\n", s2) 4

Here we convert s to an array of runes 1. We change the first element ofthis array 2. Then we create a new string s2 with the alteration 3.Finally, we print the string with fmt.Printf 4.