golang学习之--struct类型

来源:互联网 发布:韩春雨 知乎精华 编辑:程序博客网 时间:2024/05/31 19:51

GO语言中的struct和c或其他语言一样,我们可以声明新的类型

eg:

type Human struct {

name string 

age int

}


package mainimport (. "fmt". "strconv")type Human struct {name  stringage   intsex   stringphone string}type student struct {Human // 匿名字段sno   stringphone string}type teacher struct {Human //匿名字段tno   stringphone string}type print interface { //定义一个接口,但凡实现了String()方法的类型也就实现了这个接口String() string}type personalPhone interface {print //嵌入的interfacesetPhone(phone string)}func (h Human) String() string { //Human类型的String()方法return "The hunman's name is " + h.name + " age is " + Itoa(h.age) + " sex is " + h.sex + " phone is " + h.phone}func (s student) String() string { //Student类型的String()方法return "The student's name is " + s.name + " age is " + Itoa(s.age) + " sex is " + s.sex + " personal phone is " + s.phone + " phone is " + s.Human.phone}func (t teacher) String() string { //Teacher类型的String()方法return "The teacher's name is " + t.name + " age is " + Itoa(t.age) + " sex is " + t.sex + " personal phone is " + t.phone + " phone is " + t.Human.phone}func (s *student) setPhone(phone string) {s.Human.phone = phone}func (s *student) setSno(sno string) {s.sno = sno}func (t *teacher) setPhone(phone string) {t.Human.phone = phone}func (t *teacher) setTno(tno string) {t.tno = tno}func main() {h := Human{"yuhanhu", 22, "men", "13307149145"} //初始化赋值s := student{Human{"fanzhang", 22, "men", "13012526545"}, "1110322133", "13307149168"}t := teacher{Human{"viease", 28, "men", "13104715426"}, "110101", "12312312313"}p := make([]print, 3) //slice,interface, channel需要用makep[0], p[1], p[2] = h, s, tfor _, i := range p {Println(i)}pp := make([]personalPhone, 2)pp[0], pp[1] = &s, &tpp[0].setPhone("110")pp[1].setPhone("119")Println(pp[0])Println(pp[1])}


0 0
原创粉丝点击