该场景是传递具有公共字段的类似结构,并将它们设置为作为参数传递的值:
package main
type A struct {
Status int
}
type B struct {
id string
Status int
}
// It's okay to pass by value because content is only used inside this
func foo(v interface{}, status int) {
switch t := v.(type) {
case A, B:
t.Status = status // ERROR :-(
}
}
func main() {
a := A{}
foo(a, 0)
b := B{}
b.id = "x"
foo(b, 1)
}
令我沮丧的是,我收到此错误:
➜ test go run test.go
# command-line-arguments
./test.go:15: t.Status undefined (type interface {} has no field or method Status)
如果类型转换将 interface{} 转换为底层类型,我做错了什么?
GCT1015
相关分类