微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Golang(4)Struct Type and Object Oriented

Golang(4)Struct Type and Object Oriented

2.4 Struct Type
type person struct {
name string
age int
}

var P person
P.name = “sillycat”
P.age = 32

P := person{“Kiko”,18}
P := person{age:24,name:”Kiko"}

P is a pointer *person
P := new(person)

Compare the age function
return value will be the older person and the age difference
fund Older(p1,p2 person) (person,int) {
if p1.age > p2.age {
return p1,p1.age - p2.age
}
return p2,p2.age-p1.age
}

var tom person
tom.name,tom.age = “Tom”,18

tb_Older,tb_diff := Older(tom,bob)

struct hidden property
Something like extend based Class

type Human struct {
name string
age int
weight int
}

type Student struct{
Human // all the properties will be in this struct then
speciality string
}

mark:=Student{Human{“Mark”,26,120},“Computer”}
mark.age,mark.weight

mark.Human = Human{“marcus”,55,220}
mark.Human.age = 1

Define other Type
type Skills []string

type Student struct {
Human //hidden property
Skills //hidden property
int //hidden property
speciality string
}

jane := Student{Human:Human{“Jane”,35,100},speciality:”biology"}
jane.Skills = []string{“anotomy”}
jane.Skills = append(jane.Skills,“physics”,“golang”)
jane.int = 3

2.5 Object Oriented
method

Old way is struct and func calculate the area
type Rectangle struct {
width,height float64
}

fund area(r Rectangle) float64{
return r.width*r.height
}

Method area() will belong to Rectangle,A method is a function with an implicit first argument,called a receiver.

func (r ReceiverType) funcName(parameters) (results)

type Rectangle struct {
width,height float64
}
type Circle struct {
radius float64
}
func (r Rectangle) area() float64{
return r.width*r.height
}
func (c Circle) area() float64{
return c.radius * c.radius * math.Pi
}

Alias for the Type/ Customer Type
type ages int
type months map[string]int

Pointer as Receiver
when you want to change the value
func(b *Box)setColor(c Color){
…snip...
}

method extension
type Human struct{
name string
..snip...
}

type Student struct{
Human
school string
}

type Employee struct {
Human
company string
}

func (h Human) hi(){
…snip...
}

mark :=Student…snip…
sam := Emloyee…snip…
mark.hi()
sam.hi()

Override the method
func (e Employee) hi(){
..snip...
}

2.6 Interface
…snip...


References:
https://github.com/astaxie/build-web-application-with-golang/blob/master/ebook/02.4.md

Golang1 ~ 3
http://sillycat.iteye.com/blog/2037798
http://sillycat.iteye.com/blog/2047158
http://sillycat.iteye.com/blog/2052936

原文地址:https://www.jb51.cc/go/190985.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐