加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang学习之--struct类型

发布时间:2020-12-16 18:45:05 所属栏目:大数据 来源:网络整理
导读: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 // 匿名字

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])
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读