英文:
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在语句末尾
英文:
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
答案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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论