[英]How to iterate over different types in loop in Go?
在Go中,为了遍历数组/切片,您可以编写如下代码:
for _, v := range arr {
fmt.Println(v)
}
但是,我想遍历包括不同类型(int,float64,string等)的数组/切片。 在Python中,我可以这样写:
a, b, c = 1, "str", 3.14
for i in [a, b, c]:
print(i)
我如何在Go中做这样的工作? 据我所知,数组和切片都应该只允许相同类型的对象,对吗? (例如, []int
仅允许使用int
类型的对象。)
谢谢。
由于Go是一种静态类型的语言,因此不会像Python那样简单。 您将不得不使用类型断言,反射或类似方式。
看一下这个例子:
package main
import (
"fmt"
)
func main() {
slice := make([]interface{}, 3)
slice[0] = 1
slice[1] = "hello"
slice[2] = true
for _, v := range slice {
switch v.(type) {
case string:
fmt.Println("We have a string")
case int:
fmt.Println("That's an integer!")
// You still need a type assertion, as v is of type interface{}
fmt.Printf("Its value is actually %d\n", v.(int))
default:
fmt.Println("It's some other type")
}
}
}
在这里,我们用一个空接口的类型构造一个切片(任何类型都可以实现),进行类型切换并基于该结果处理值。
不幸的是,您将在处理未指定类型(空接口)的数组的任何地方都需要此方法(或类似方法)。 而且,除非您有办法处理可能得到的任何对象,否则可能需要为每种可能的类型加上大小写。
一种方法是使要存储的所有类型都实现您自己的某个接口,然后仅通过该接口使用那些对象。 这就是fmt
处理通用参数的方式–它只是在任何对象上调用String()
以获取其字符串表示形式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.