How do I measure string length in bytes vs runes?

This example demonstrates how to measure the length of a string in Go both in bytes and in runes. The byte length counts each character based on how many bytes they take, while the rune length counts each Unicode character, which can differ in size.
Go, string length, bytes, runes, utf8, programming, example
<?php package main import ( "fmt" "unicode/utf8" ) func main() { str := "Hello, 世界" // Example string containing both ASCII and non-ASCII characters // Length in bytes byteLength := len(str) fmt.Printf("Byte length: %d\n", byteLength) // Length in runes (Unicode characters) runeLength := utf8.RuneCountInString(str) fmt.Printf("Rune length: %d\n", runeLength) } ?>

Go string length bytes runes utf8 programming example