"len()" is a function used to obtain the length or number of elements of strings, arrays, slices, dictionaries, channels, etc. The specific usage is "len (name of the element being obtained)", But for strings, the "len()" function returns the number of bytes in the string, not the number of characters.
# Operating system for this tutorial: Windows 10 system, Dell G3 computer.
In the Go language, the len() function is used to obtain the length or number of elements of strings, arrays, slices, dictionaries, channels, etc. The specific usage is as follows:
s := "hello, world!" length := len(s) // length为13
arr := [3]int{1, 2, 3} length := len(arr) // length为3
slice := []int{1, 2, 3} length := len(slice) // length为3
dict := map[string]int{"a": 1, "b": 2, "c": 3} length := len(dict) // length为3
ch := make(chan int, 3) ch <- 1 ch <- 2 ch <- 3 length := len(ch) // length为3
It should be noted that for strings, the len() function returns the number of bytes of the string, not the number of characters. For non-ASCII characters such as Chinese characters, one character may occupy multiple bytes, so you need to use the utf8.RuneCountInString() function to get the number of characters. For example:
s := "你好,世界!" byteLength := len(s) // byteLength为15 runeLength := utf8.RuneCountInString(s) // runeLength为6
In addition to the above types, the len() function can also be used to obtain the capacity of arrays, slices and dictionaries, as well as the capacity of byte arrays of string, []byte and other types. For example:
// 获取切片容量 slice := make([]int, 3, 5) capacity := cap(slice) // capacity为5 // 获取字节数组容量 str := "hello" byteCapacity := cap([]byte(str)) // byteCapacity为6
In short, the len() function is a very commonly used function in the Go language, which can easily obtain the length or number of elements of the data structure.
The above is the detailed content of What function is len. For more information, please follow other related articles on the PHP Chinese website!