Sobes.tech
Junior — Middle

How can the length of a string be determined in a program?

sobes.tech AI

Answer from AI

In Go, the length of a string can be determined using the built-in len() function. It returns the number of bytes in the string, since strings in Go are sequences of bytes in UTF-8 encoding.

Example:

package main
import "fmt"

func main() {
    s := "Привет"
    fmt.Println(len(s)) // Will output the number of bytes, not characters
}

If you need to get the number of characters (runes), you can convert the string to a slice of runes:

runes := []rune(s)
fmt.Println(len(runes)) // Number of characters

Thus, for the length of a string in bytes, use len(), and for the length in characters, convert to []rune and then use len().

How can the length of a string be determined in a… - sobes.tech