package main import "fmt" func main() { s := "golang" slice := s[1:4] fmt.Println(s) fmt.Println(slice) }
The slice s[1:4] takes characters from index 1 up to but not including index 4. So it extracts characters at positions 1, 2, and 3 which are 'o', 'l', and 'a'.
The original string remains unchanged and prints as "golang".
package main
func main() {
s := "hello"
s[0] = 'H'
}In Go, strings are immutable byte sequences. Trying to assign a value to an index of a string causes a compilation error.
package main import "fmt" func main() { s := "hello" b := []byte(s) b[0] = 'H' fmt.Println(s) fmt.Println(string(b)) }
The byte slice b is a copy of the string s's bytes. Changing b does not affect s.
So s prints as "hello" and b prints as "Hello" after modification.
The pointer in the string header points to the first byte of the string data in memory, allowing the string to access its bytes.
package main import "fmt" func main() { s := "δ½ ε₯½ε" b := []byte(s) fmt.Println(len(s)) fmt.Println(len(b)) }
The string "δ½ ε₯½ε" has 3 characters (runes) but each Chinese character uses 3 bytes in UTF-8 encoding, totaling 9 bytes.
In Go, len(s) returns the number of bytes, not the number of runes. len(b) for the byte slice also returns 9.
