This is a creation in Article, where the information may have evolved or changed.
The go language can declare new types through structs
Create a new type person
typestruct { string int}var'liming'p1.age = 18
Create a new type student, you can introduce the person all characters De Yin by anonymous field student
typestruct { Person //隐式引入 string string}s1 := Student{Person{'zhangliang',23'hign school','new name'}s1.age //23 可直接访问Person的字段s1.name //new name 最外层优先访问,重载//zhangliang 通过匿名字段访问
Add a recipient struct to a function, or add a method to a struct
//此处传递是按值传递的,操作的是副本,若receiver为指针,则按引用传递,操作的是原实例对象boolean { if18 { //可以直接访问struct的字段 returntrue } returnfalse} s1.isAdult() //trueintboolean { s.age = newAge }s1.changeAge(23)
Method is the same as the inheritance of the field, all through the anonymous field
type HignSchoolStudet { Student string}//可函数重载funcint) boolean { h.age = newAge + 12}h1 := HignSchoolStudet{Student{Person{'zhangliang',23'hign school'},'math'}
The interface interface, which provides a combination of common methods, provides a dynamic type
type people interface {changeage ()}
var i peoplei = S1S1. Changeage () i = H1h1. Age