douding_1073 2011-01-09 16:56
浏览 34

如何在Go中子类化

In C I can do something like this

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);

Using this approach, I can pass any struct(Circle,Rectangle,etc) that has struct Point as first member. How can I do the same in google go?

  • 写回答

2条回答 默认 最新

  • duanqiang5722 2011-01-09 18:09
    关注

    Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy. The concept of “interface” in Go provides a different approach that we believe is easy to use and in some ways more general. There are also ways to embed types in other types to provide something analogous—but not identical—to subclassing. Is Go an object-oriented language?, FAQ.

    For example,

    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)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大