免責聲明

Disclaimer (免責聲明)
繼續閱覽代表您接受以上的免責聲明.
To continue reading means you accept the above disclaimer.

2015年3月30日 星期一

golang struct and interface


http://www.golang-book.com/9/index.htm

"""...
type Circle struct {
x float64
y float64
r float64
}

func (c *Circle) area() float64 {
return math.Pi * c.r*c.r
}

[member function for 'class' Circle]
... In between the keyword func and the name of the function we've added a “receiver”.


c := new(Circle)
c := Circle{x: 0, y: 0, r: 5}
c := Circle{0, 0, 5}


...
type Rectangle struct {
x1, y1, x2, y2 float64
}
func (r *Rectangle) area() float64 {
l := distance(r.x1, r.y1, r.x1, r.y2)
w := distance(r.x1, r.y1, r.x2, r.y1)
return l * w
}



... able to name the Rectangle's area method the same thing as the Circle's area method. This was no accident

Go has a way of making these accidental similarities explicit through a type known as an Interface. Here is an example of a Shape interface:

type Shape interface {
area() float64
}


..."""



[anonymous field / embedded type ]

type Person struct {
Name string
}
func (p *Person) Talk() {
fmt.Println("Hi, my name is", p.Name)
}

* Android has a Person
type Android struct {
Pson Person
Model string
}
... we would rather say an Android is a Person, rather than an Android has a Person.

type Android struct {
Person //unamed field of type Person
Model string
}

-->
a := new(Android)
a.Talk() //skip the Person field



沒有留言:

張貼留言