How to Find Length of String in Go: Simple Guide
In Go, you find the length of a string using the
len() function. It returns the number of bytes in the string, which is the string's length in bytes, not necessarily the number of characters.Syntax
The syntax to find the length of a string in Go is simple:
len(s): wheresis your string variable.- This returns an integer representing the number of bytes in the string.
go
len(s)Example
This example shows how to use len() to get the length of a string and print it.
go
package main import ( "fmt" ) func main() { s := "Hello, Go!" length := len(s) fmt.Println("Length of string:", length) }
Output
Length of string: 10
Common Pitfalls
One common mistake is assuming len() returns the number of characters. It actually returns the number of bytes. For strings with special or non-ASCII characters, this can be different.
For example, emojis or accented letters use more than one byte each.
To count characters (runes), you need to convert the string to a rune slice.
go
package main import ( "fmt" ) func main() { s := "Go ❤️" fmt.Println("Byte length:", len(s)) // counts bytes fmt.Println("Character count:", len([]rune(s))) // counts characters }
Output
Byte length: 6
Character count: 4
Quick Reference
| Function | Description |
|---|---|
| len(s) | Returns the number of bytes in string s |
| len([]rune(s)) | Returns the number of characters (runes) in string s |
Key Takeaways
Use len(s) to get the byte length of a string in Go.
len() counts bytes, not characters, so multi-byte characters affect the count.
Convert string to []rune to count actual characters.
Remember that len() returns an integer representing length in bytes.
For simple ASCII strings, len() matches character count.