方案是使用公共字段传递类似的结构,并将这些结构设置为作为params传递的值:
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)如果类型广播将接口{}转换为基础类型,那么我做错了什么?
发布于 2015-07-29 04:39:08
尽管A和B都有状态字段,但它们不能与类型系统互换。你们每个人都必须有单独的箱子。
case A:
t.Status = status
case B:
t.Status = status
} 或者,您可以使用一个实际的接口:
type HasStatus interface {
SetStatus(int)
}
type A struct {
Status int
}
func (a *A) SetStatus(s int) { a.Status = s }
func foo(v HasStatus, status int) {
v.SetStatus(status)
}如果您有多个类型,所有这些类型都有一组公共字段,则可能需要使用嵌入式结构:
type HasStatus interface {
SetStatus(int)
}
type StatusHolder struct {
Status int
}
func (sh *StatusHolder) SetStatus(s int) { sh.Status = s }
type A struct {
StatusHolder
}
type B struct {
id string
StatusHolder
}https://stackoverflow.com/questions/31691193
复制相似问题