英文:
How to use passed struct in function
问题
我看到过某个地方,但我不记得是哪里了,一个切片结构体通过以下代码片段的函数。
package main
import "fmt"
func passSlice(arg interface{}) {
fmt.Println(arg)
}
func main() {
res := []struct {
Name string
}{}
passSlice(res)
}
我不知道如何在函数中使用切片结构体。有人有想法吗?我该如何在函数中使用它?
英文:
I saw somewhere, but I do not remember where, that a slice struct is passing through function like the following code snippet.
package main
import "fmt"
func passSlice(arg interface{}) {
fmt.Println(arg)
}
func main() {
res := []struct {
Name string
}{}
passSlice(res)
}
I have no idea, how to use here a slice struct in the function. Have someone a idea, how can I use it in the function?
答案1
得分: 2
为了使用slice结构体(或存储在interface中的任何其他值),你必须首先进行**类型断言或类型切换**:
类型断言:
func passSlice(arg interface{}) {
// 如果arg的值是[]struct{ Name string }类型,则将其值存入v中
v, ok := arg.([]struct{ Name string })
if !ok {
// 不包含类型为[]struct{Name string}的值
return
}
for _, s := range v {
fmt.Println(s.Name)
}
}
Playground: http://play.golang.org/p/KiFeVC3VQ_
类型切换类似,但可以有多个类型的情况。
还有一种使用reflect
包的选项,允许您更动态地处理接口值,而不需要事先知道可以预期的类型,但使用反射也更复杂。要了解更多关于在Golang中使用反射的信息,您可以查看以下链接:
英文:
In order to use the slice struct (or any other value stored in an interface), you must first do a type assertion or type switch:
Type assertion:
func passSlice(arg interface{}) {
// Put args value in v if it is of type []struct{ Name string }
v, ok := arg.([]struct{ Name string })
if !ok {
// did not contain a value of type []struct{Name string}
return
}
for _, s := range v {
fmt.Println(s.Name)
}
}
Playground: http://play.golang.org/p/KiFeVC3VQ_
Type switches are similar, but can have cases for multiple types.
There is also an option of using the reflect
package, allowing you to more dynamically handle interface values without knowing before hand what types you can expect, but using reflection is also more complex. To know more about using reflection in Golang, you can look here:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论