duandanbeng1829 2012-09-21 18:56
浏览 31
已采纳

Go结构体可以继承一组值吗?

Can a Go struct inherit a set of values from a type of another struct?

Something like this.

type Foo struct {
    Val1, Val2, Val3 int
}

var f *Foo = &Foo{123, 234, 354}

type Bar struct {
    // somehow add the f here so that it will be used in "Bar" inheritance
    OtherVal string
}

Which would let me do this.

b := Bar{"test"}
fmt.Println(b.Val2) // 234

If not, what technique could be used to achieve something similar?

  • 写回答

1条回答 默认 最新

  • dongpu7881 2012-09-21 19:03
    关注

    Here's how you may embed the Foo struct in the Bar one :

    type Foo struct {
        Val1, Val2, Val3 int
    }
    type Bar struct {
        Foo
        OtherVal string
    }
    func main() {
        f := &Foo{123, 234, 354}
        b := &Bar{*f, "test"}
        fmt.Println(b.Val2) // prints 234
        f.Val2 = 567
        fmt.Println(b.Val2) // still 234
    }
    

    Now suppose you don't want the values to be copied and that you want b to change if f changes. Then you don't want embedding but composition with a pointer :

    type Foo struct {
        Val1, Val2, Val3 int
    }
    type Bar struct {
        *Foo
        OtherVal string
    }
    func main() {
        f := &Foo{123, 234, 354}
        b := &Bar{f, "test"}
        fmt.Println(b.Val2) // 234
        f.Val2 = 567
        fmt.Println(b.Val2) // 567
    }
    

    Two different kind of composition, with different abilities.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?