Inheritance in Golang can be achieved by including anonymous structures in the structure. Specifically, for example, if the structure of iPhone needs to be inherited, the structure of phone can be written as follows:

 package main

import "fmt"

type phone struct {
    design_place     string
    production_place string
}

type iphone struct {
    brand string
    phone
}

func main() {
    thePhone := phone{
        design_place:     "California",
        production_place: "China",
    }
    thisPhone := iphone{
        brand: "Apple",
        phone: thePhone,
    }

    fmt.Println(thisPhone.production_place, thisPhone.brand)
}

LiberHome
409 声望1.1k 粉丝

有问题 欢迎发邮件 📩 liberhome@163.com