为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 interface{} 作为通配符类型?

如何使用 interface{} 作为通配符类型?

Go
万千封印 2021-10-25 17:19:09
该场景是传递具有公共字段的类似结构,并将它们设置为作为参数传递的值:package maintype A struct {    Status int}type B struct {    id     string    Status int}// It's okay to pass by value because content is only used inside thisfunc 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{} 转换为底层类型,我做错了什么?
查看完整描述

1 回答

?
GCT1015

TA贡献1827条经验 获得超4个赞

尽管 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

}


查看完整回答
反对 回复 2021-10-25
  • 1 回答
  • 0 关注
  • 217 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信