Go语言 – 接口和数组

huangapple go评论161阅读模式
英文:

Go Lang - Interfaces and arrays

问题

我有一个变量,我认为它的类型是"[]interface {}"。

  1. 如何检测它的类型?
  2. 如何转换为数组?

以下是代码:

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 {}"

  1. How do i detect it
  2. 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

huangapple
  • 本文由 发表于 2014年1月31日 15:57:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/21475032.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定