In Go, len is a very common built-in function that is used to get the length or size of various data types. Mastering the use of len can help us process data structures more efficiently. This article will introduce in detail the usage scenarios and examples of the len function.
Use scenarios of len function
The len function can be used in the following data types:
- Array
- slice
- string
- Map (map)
- Channel (channel)
len in array and slice
For arrays and slices, the len function returns the number of elements.
package main import "fmt" func main() { //Array example arr := [5]int{1, 2, 3, 4, 5} ("Array Length:", len(arr)) // Output: Array length: 5 // Slice example slice := []int{1, 2, 3, 4, 5} ("Slice length:", len(slice)) // Output: Slice length: 5}
len in string
For strings, the len function returns the number of bytes, not the number of characters. This requires special attention when dealing with multibyte characters (such as Chinese).
package main import "fmt" func main() { str := "Hello, the world" ("String length (byte number):", len(str)) // Output: string length (byte number): 13}
len in map
For mappings, the len function returns the number of key-value pairs.
package main import “fmt” func main() { m := map[string]int{“a”: 1, “b”: 2, “c”: 3} (“Map length:”, len(m)) // Output: Map length: 3}
len in the channel
For channels, the len function returns the number of unread elements in the current buffer. Note that only channels with buffers have this meaning.
package main import "fmt" func main() { ch := make(chan int, 5) ch <- 1 ch <- 2 ("Channel Length:", len(ch)) // Output: Channel length: 2}
Notes on using len function
- Characters and Bytes: For strings, len returns the number of bytes instead of characters. If you need to get the number of characters, you can use the function.
- Dynamic length: The lengths of slices, maps, and channels are dynamic and can be changed at runtime, so the value returned by len also changes.
- Performance Considerations: The len function is a constant time operation, even for maps and channels, because they maintain length information internally.
Summarize
len is a simple but powerful built-in function in Go language that helps us easily get the length or size of a data structure. Whether it is an array, slice, string, map or channel, len returns the required information quickly and accurately. When writing Go code, making full use of len functions can improve the readability and efficiency of your code.
This is the end of this article about the use of built-in function len in Go language. For more related contents of built-in function len in Go language, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!