golang学习之--struct类型

前端之家收集整理的这篇文章主要介绍了golang学习之--struct类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

eg:

type Human struct {

name string

age int

}


package main


import (
. "fmt"
. "strconv"
)


type Human struct {
name  string
age   int
sex   string
phone string
}
type student struct {
Human // 匿名字段
sno   string
phone string
}
type teacher struct {
Human //匿名字段
tno   string
phone string
}
type print interface { //定义一个接口,但凡实现了String()方法的类型也就实现了这个接口
String() string
}
type personalPhone interface {
print //嵌入的interface
setPhone(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","13012526545"},"1110322133","13307149168"}
t := teacher{Human{"viease",28,"13104715426"},"110101","12312312313"}
p := make([]print,3) //slice,interface, channel需要用make
p[0],p[1],p[2] = h,s,t


for _,i := range p {
Println(i)
}


pp := make([]personalPhone,2)
pp[0],pp[1] = &s,&t
pp[0].setPhone("110")
pp[1].setPhone("119")


Println(pp[0])
Println(pp[1])
}
原文链接:https://www.f2er.com/go/190522.html

猜你在找的Go相关文章