packagemainimport"fmt"typeHumanstruct{// 定义一个“Human” structnamestringageintphonestring}typeStudentstruct{Human//匿名字段 // 继承Human 的属性schoolstringloanfloat32}typeEmployeestruct{Human//匿名字段 // 继承Human 的属性companystringmoneyfloat32}//Human实现SayHi方法func(hHuman)SayHi(){fmt.Printf("Hi, I am %s you can call me on %s\n",h.name,h.phone)}//Human实现Sing方法func(hHuman)Sing(lyricsstring){fmt.Println("La la la la...",lyrics)}//Employee重载Human的SayHi方法func(eEmployee)SayHi(){fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n",e.name,e.company,e.phone)}// Interface Men被Human,Student和Employee实现// 因为这三个类型都实现了这两个方法typeMeninterface{SayHi()Sing(lyricsstring)}funcmain(){mike:=Student{Human{"Mike",25,"222-222-XXX"},"MIT",0.00}paul:=Student{Human{"Paul",26,"111-222-XXX"},"Harvard",100}sam:=Employee{Human{"Sam",36,"444-222-XXX"},"Golang Inc.",1000}tom:=Employee{Human{"Tom",37,"222-444-XXX"},"Things Ltd.",5000}//定义Men类型的变量ivariMen//i能存储Studenti=mikefmt.Println("This is Mike, a Student:")i.SayHi()i.Sing("November rain")//i也能存储Employeei=tomfmt.Println("This is tom, an Employee:")i.SayHi()i.Sing("Born to be wild")//定义了slice Menfmt.Println("Let's use a slice of Men and see what happens")x:=make([]Men,3)//这三个都是不同类型的元素,但是他们实现了interface同一个接口x[0],x[1],x[2]=paul,sam,mikefor_,value:=rangex{value.SayHi()}}
packagemainimport("fmt""strconv")typeHumanstruct{namestringageintphonestring}// 通过这个方法 Human 实现了 fmt.Stringerfunc(hHuman)String()string{return"❰"+h.name+" - "+strconv.Itoa(h.age)+" years - ✆ "+h.phone+"❱"}funcmain(){Bob:=Human{"Bob",39,"000-7777-XXX"}fmt.Println("This Human is : ",Bob)}
packagemainimport("fmt")funcmain(){varvWriterCloser=&myWriterCloser{}//遇到下面的调用的方式时,必须使用指针传递,/* 否则将会报错《./main.go:8:6: cannot use composite literal (type myWriterCloser) as type WriterCloser in assignment:
myWriterCloser does not implement WriterCloser (Write method has pointer receiver)》
*/fmt.Println(v)}typeWriterinterface{Write([]byte)(int,error)}typeCloserinterface{Close()error}typeWriterCloserinterface{WriterCloser}typemyWriterCloserstruct{}func(m*myWriterCloser)Write(data[]byte)(int,error){// 这里使用了指针传递。return0,nil}func(mmyWriterCloser)Close()error{//这里使用了值传递。go runtime 会自动进行解指针操作,而使得程序正常运行。returnnil}