对象和组合
package main import ( "fmt" ) type father struct { name string sex int } type sun struct { father age int } func main() { m:=father{name:"father",sex:11} s:=sun{father:father{name:"son",sex:12},age:14} fmt.Println(s) fmt.Println("name",s.name) fmt.Println("name",m.name) fmt.Println("sex",s.sex) fmt.Println("sex",m.sex) fmt.Println("age",s.age) }
接口实例:
package main import "fmt" //接口,只是一个提示,不在接口定义中实现 type Handler interface { Do(k, v interface{}) } //使用接口 func Each(m map[string]int, h Handler) { if m != nil && len(m) > 0 { for k, v := range m { h.Do(k, v) } } } type welcome string //接口实现处 func (w welcome) Do(k, v interface{}) { fmt.Printf("%s,我叫%s,今年%d岁\n", w,k, v) } func main(){ persons := make(map[string]int) persons["张三"] = 20 persons["李四"] = 23 persons["王五"] = 26 var w welcome = "大家好" Each(persons, w) }
有疑问加站长微信联系(非本文作者)