猿问

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

该场景是传递具有公共字段的类似结构,并将它们设置为作为参数传递的值:


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{} 转换为底层类型,我做错了什么?


万千封印
浏览 218回答 1
1回答

GCT1015

尽管 A 和 B 都有一个状态字段,但它们不能与类型系统互换。您必须为每个案例设置单独的案例。case A:    t.Status = statuscase 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}
随时随地看视频慕课网APP

相关分类

Go
我要回答