Go Interface Fields

后端 未结 2 1318
野性不改
野性不改 2020-12-12 11:24

I\'m familiar with the fact that, in Go, interfaces define functionality, rather than data. You put a set of methods into an interface, but you are unable to specify any fi

2条回答
  •  一向
    一向 (楼主)
    2020-12-12 12:11

    If I correctly understand you want to populate one struct fields into another one. My opinion not to use interfaces to extend. You can easily do it by the next approach.

    package main
    
    import (
        "fmt"
    )
    
    type Person struct {
        Name        string
        Age         int
        Citizenship string
    }
    
    type Bob struct {
        SSN string
        Person
    }
    
    func main() {
        bob := &Bob{}
    
        bob.Name = "Bob"
        bob.Age = 15
        bob.Citizenship = "US"
    
        bob.SSN = "BobSecret"
    
        fmt.Printf("%+v", bob)
    }
    

    https://play.golang.org/p/aBJ5fq3uXtt

    Note Person in Bob declaration. This will be made the included struct field be available in Bob structure directly with some syntactic sugar.

提交回复
热议问题