Home  >  Article  >  Backend Development  >  What function is len

What function is len

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2023-12-18 15:00:191956browse

"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.

What function is len

# 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:

  1. Get the string length:
s := "hello, world!"
length := len(s)  // length为13
  1. Get the array length:
arr := [3]int{1, 2, 3}
length := len(arr)  // length为3
  1. Get the slice Length:
slice := []int{1, 2, 3}
length := len(slice)  // length为3
  1. Get the number of elements in the dictionary:
dict := map[string]int{"a": 1, "b": 2, "c": 3}
length := len(dict)  // length为3
  1. Get the number of elements in the channel buffer:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn