英文:
Go Lang - Interfaces and arrays
问题
我有一个变量,我认为它的类型是"[]interface {}"。
- 如何检测它的类型?
- 如何转换为数组?
以下是代码:
var s string
switch value1 := value1.(type) {
case int:
s = strconv.Itoa(value1)
case float64:
s = strconv.FormatFloat(value1, 'f', 0, 64)
//case array:
//fmt.Printf("array")
default :
fmt.Printf("\nvalue=v+%",value1)
}
输出结果为:
value=v+%!(NOVERB)%!(EXTRA []interface {}=
英文:
I have a variable that i think is of type "[]interface {}"
- How do i detect it
- Convert to array ?
Here's the code:
var s string
switch value1 := value1.(type) {
case int:
s = strconv.Itoa(value1)
case float64:
s = strconv.FormatFloat(value1, 'f', 0, 64)
//case array:
//fmt.Printf("array")
default :
fmt.Printf("\nvalue=v+%",value1)
}
And the output is:
value=v+%!(NOVERB)%!(EXTRA []interface {}=
答案1
得分: 6
你可以像其他类型一样,在类型切换中选择一个切片。例如:
switch v := value1.(type) {
case []interface{}:
for _, element := range v {
fmt.Println(element)
}
}
你可以在这里尝试这个例子:http://play.golang.org/p/4z9eejp4BL
英文:
You can select for a slice in a type switch the same as other types. For example:
switch v := value1.(type) {
case []interface{}:
for _, element := range v {
fmt.Println(element)
}
}
You can play with this example here: http://play.golang.org/p/4z9eejp4BL
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论