乐闻世界logo
搜索文章和话题

What is the purpose of the range keyword in Go?

1个答案

1

The range keyword in Go is highly useful for iterating over arrays, slices, strings, or maps. Using range enables a more concise and clear traversal of elements.

Usage Examples

1. Traversing Arrays or Slices

When using range to iterate over arrays or slices, it returns two values: the index of the element and a copy of the element.

go
nums := []int{10, 20, 30, 40} for index, value := range nums { fmt.Printf("Index: %d, Value: %d\n", index, value) }

2. Traversing Strings

When traversing strings, range returns the index of the character and its Unicode code point, rather than the byte position.

go
s := "Hello, 世界" for index, runeValue := range s { fmt.Printf("%#U starts at byte position %d\n", runeValue, index) }

Here, runeValue is a Unicode code point of type rune.

3. Traversing Maps

When traversing maps, range returns key-value pairs.

go
m := map[string]int{"a": 1, "b": 2} for key, value := range m { fmt.Printf("Key: %s, Value: %d\n", key, value) }

4. Traversing Only Keys or Values

If only keys or values are required, the blank identifier _ can be used to ignore the other return values.

go
// Traversing only keys for key := range m { fmt.Println("Key: ", key) } // Traversing only values for _, value := range m { fmt.Println("Value: ", value) }

Summary

range provides a concise and efficient way to traverse elements within data structures, making the code both clearer and easier to maintain. In Go, it is one of the preferred tools for handling collection data types.

2024年8月7日 18:15 回复

你的答案