Mental Model
A string is a sequence of characters you can look at one by one from start to end.
Analogy: Imagine reading a sentence letter by letter with your finger pointing to each character in order.
S -> t -> r -> i -> n -> g -> null ā
S -> t -> r -> i -> n -> g -> null ā
G -> o -> ! -> null ā
G -> o -> ! -> null ā
G -> o -> ! -> null
āG -> o -> ! -> null
āG -> o -> ! -> null
āG -> o -> ! -> null Printed characters: G\no\n!\n
package main import "fmt" func main() { s := "Go!" for i := 0; i < len(s); i++ { // Access character at index i c := s[i] fmt.Printf("%c\n", c) // Print character } }
for i := 0; i < len(s); i++ {c := s[i]fmt.Printf("%c\n", c)for i := 0; i < len(s); i++ {
for i := 0; i < len(s); i++ {
len(s) return when s is a string in Go?len does on strings in Golen(s) returns the number of bytes, not characters, because strings are byte slices.len counts bytes, not runes.s in Go?s[2] is valid Go syntax for accessing a byte at index 2.package main
import "fmt"
func main() {
s := "GoLang"
fmt.Println(string(s[1]))
}string(s[1]) converts byte 'o' to string "o".package main
import "fmt"
func main() {
s := "hello"
for i := 0; i <= len(s); i++ {
fmt.Printf("%c", s[i])
}
}s containing Unicode characters, which Go code snippet correctly prints each character (rune) on a new line?range loop.for _, r := range s which iterates runes correctly and prints each rune as string.Pass the test and this pattern moves unknown