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
Golang(4)Struct Type and Object Oriented
最新推荐文章于 2025-07-25 01:28:23 发布