在CI中可以做这样的事情
struct Point {
int x,y;
}
struct Circle {
struct Point p; // must be first!
int rad;
}
void move(struct Point *p,int dx,int dy) {
....
}
struct Circle c = .....;
move( (struct Point*)&c,1,2);
Run Code Online (Sandbox Code Playgroud)
使用这种方法,我可以传递任何具有struct Point作为第一个成员的结构(Circle,Rectangle等).我怎么能在谷歌去做同样的事情?
Ros*_*ght 13
实际上,有一种更简单的方法,它更类似于OP的例子:
type Point struct {
x, y int
}
func (p *Point) Move(dx, dy int) {
p.x += dx
p.y += dy
}
type Circle struct {
*Point // embedding Point in Circle
rad int
}
// Circle now implicitly has the "Move" method
c := &Circle{&Point{0, 0}, 5}
c.Move(7, 3)
Run Code Online (Sandbox Code Playgroud)
另请注意,Circle还将实现PeterSO发布的Mover界面.
http://golang.org/doc/effective_go.html#embedding
尽管Go具有类型和方法,并且允许面向对象的编程风格,但是没有类型层次结构.Go中"接口"的概念提供了一种我们认为易于使用且在某些方面更为通用的不同方法.还有一些方法可以将类型嵌入到其他类型中,以提供类似但不完全相同的子类化.Go是一种面向对象的语言吗?
例如,
package main
import "fmt"
type Mover interface {
Move(x, y int)
}
type Point struct {
x, y int
}
type Circle struct {
point Point
rad int
}
func (c *Circle) Move(x, y int) {
c.point.x = x
c.point.y = y
}
type Square struct {
diagonal int
point Point
}
func (s *Square) Move(x, y int) {
s.point.x = x
s.point.y = y
}
func main() {
var m Mover
m = &Circle{point: Point{1, 2}}
m.Move(3, 4)
fmt.Println(m)
m = &Square{3, Point{1, 2}}
m.Move(4, 5)
fmt.Println(m)
}
Run Code Online (Sandbox Code Playgroud)