将interface{}转换为字符串数组

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

casting interface{} to string array

问题

我正在尝试将存储在interface[]中的数据转换回字符串数组,但遇到了一个意外的错误。

type Foo struct {
    Data interface{}
}

func (foo Foo) GetData() interface{} {
    return foo.Data
}

func (foo *Foo) SetData(data interface{}) {
    foo.Data = data
}

func main() {
    f := &Foo{}
    f.SetData([]string{"a", "b", "c"})

    var data []string = ([]string)(f.GetData())
    fmt.Println(data)
}

错误:main.go:23: 语法错误:意外的f在语句末尾

Go Playground

英文:

I'm trying to get the data which is stored in interface[] back to string array. Encountering an unexpected error.

type Foo struct {
	Data interface{}
}

func (foo Foo) GetData() interface{} {
	return foo.Data
}

func (foo *Foo) SetData(data interface{}) {
	foo.Data = data
}

func main() {
	f := &Foo{}
	f.SetData( []string{"a", "b", "c"} )
	
	var data []string = ([]string) f.GetData()
	fmt.Println(data)
}

Error: main.go:23: syntax error: unexpected f at end of statement

Go Playground

答案1

得分: 27

你正在尝试进行一种转换。类型转换有特定的规则,所有规则都可以在上面的链接中找到。简而言之,你不能将interface{}值转换为[]string

相反,你必须使用类型断言,这是一种机制,允许你(尝试)将接口类型转换为另一种类型:

var data []string = f.GetData().([]string)

链接:https://play.golang.org/p/FRhJGPgD2z

英文:

What you are trying to perform is a conversion. There are specific rules for type conversions, all of which can be seen in the previous link. In short, you cannot convert an interface{} value to a []string.

What you must do instead is a type assertion, which is a mechanism that allows you to (attempt to) "convert" an interface type to another type:

var data []string = f.GetData().([]string)

https://play.golang.org/p/FRhJGPgD2z

huangapple
  • 本文由 发表于 2017年3月12日 04:46:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/42740437.html
匿名

发表评论

匿名网友

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

确定