This is a creation in Article, where the information may have evolved or changed.
There is no class in the Golang, but there is a struct struct, a bit similar, he does not have the concept of inheriting in the java,c++, but he has a similar function of structure embedding
- Simple structure Declaration and use
type User struct{ name string age int address string}user:= User{name:"测试",age:10} user.address="广州市"f.Println(user)
person:= struct {//匿名结构 name string age int }{name:"匿名",age:1} f.Println("person:",person)
- The structure of the function as a parameter, if not with the structure pointer, the function inside the parameter attribute change does not affect the original object's property change
//值拷贝,不改变原来的User对象值func us(user User){ user.name="值拷贝"; user.age=12 user.address="珠海市" f.Println("user in us:",user)}//声明调用user:=User{}us(user)
//指针,改变原来的User对象值func use(user *User){ user.name="指针" user.age=15 user.address="深圳市" f.Println("user in use:",*user)}//声明调用user:=User{}use(&user)
- Although there is no inheritance in the go language, it can be embedded in the structure to achieve similar inheritance effects.
type Info struct { sex int name string age int address string}type User struct{ like string Info}type Admin struct { unlike string Info}user:= User{}user.sex=0user.address="广州市"user.like="游戏"f.Println(user) admin:= Admin{Info:Info{sex:1}}//还可以这样声明一些属性值,因为Info是结构体,匿名,所以需要这样声明admin.address="广州市"admin.unlike="游戏"f.Println(admin)
- If the fields of the embedded structure and the fields of the external structure are the same, then the field values that you want to modify the embedded structure need to be added with the embedded structure name declared in the external structure
type Info struct { sex int name string age int address string}type User struct{ like string sex int Info}user:=User{}user.sex=1//这里修改的外部结构User里面的sex字段值user.Info.sex=2//这里修改的是嵌入结构Info的sex字段值