在Go语言中,范围(range)用于迭代数组、切片、映射、通道等数据结构的元素。范围的语法形式为for range,可以遍历集合中的每个元素,并在每次迭代中返回元素的索引(或键)和对应的值。

(图片来源网络,侵删)
Go语言范围使用方法
使用范围语句的一般形式为:
for index, element := range collection {
// 使用 index 和 element 进行操作
}
其中,index 是元素的索引(或键),element 是集合中的元素值,collection 是要迭代的集合对象,如数组、切片、映射或通道。

(图片来源网络,侵删)
Go语言范围示例
示例1:遍历数组或切片
numbers := []int{1, 2, 3, 4, 5}
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
示例2:遍历映射
studentScores := map[string]int{ "Alice": 95, "Bob": 82, "Charlie": 67, } for name, score := range studentScores { fmt.Printf("Name: %s, Score: %d\n", name, score) }
示例3:遍历通道
ch := make(chan int)
go func() {
ch
fmt.Println(value)
}
// 遍历数组
numbers := [5]int{1, 2, 3, 4, 5}
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
// 遍历切片
fruits := []string{"apple", "banana", "orange"}
for index, value := range fruits {
fmt.Printf("Index: %d, Value: %s\n", index, value)
}
// 遍历映射
person := map[string]int{"John": 30, "Alice": 25, "Bob": 35}
for name, age := range person {
fmt.Printf("%s is %d years old\n", name, age)
}
// 遍历通道
ch := make(chan int)
go func() {
ch
fmt.Println("Received:", value)
}
}
ch := make(chan string)
go func() {
ch
fmt.Println("Received:", fruit)
}
}
numbers := []int{5, 2, 7, 1, 9}
max := numbers[0]
for _, value := range numbers {
if value max {
max = value
}
}
fmt.Println("Max value:", max)
}
numbers := []int{1, 2, 3, 4, 5}
for _, _ = range numbers {
fmt.Println("Processing element")
}
}
// 迭代切片
fruits := []string{"apple", "banana", "orange"}
for _, fruit := range fruits {
fmt.Println("Fruit:", fruit)
}
// 迭代映射
person := map[string]int{"John": 30, "Alice": 25, "Bob": 35}
for name, age := range person {
fmt.Printf("%s is %d years old\n", name, age)
}
}
ch := make(chan int)
go func() {
ch
fmt.Println("Received:", value)
}
}
ID int
Name string
Price float64
}
func main() {
// 商品列表
products := []Product{
{ID: 1, Name: "Apple", Price: 2.5},
{ID: 2, Name: "Banana", Price: 1.5},
{ID: 3, Name: "Orange", Price: 3.0},
}
// 遍历商品列表
for _, product := range products {
fmt.Printf("ID: %d, Name: %s, Price: %.2f\n", product.ID, product.Name, product.Price)
}
}








