0

以下围棋代码:

package main

import "fmt"

type Polygon struct {
    sides int
    area int
}

type Rectangle struct {
    Polygon
    foo int
}

type Shaper interface {
    getSides() int
}

func (r Rectangle) getSides() int {
    return 0
}

func main() {   
    var shape Shaper = new(Rectangle) 
    var poly *Polygon = new(Rectangle)  
}

导致此错误:

cannot use new(Rectangle) (type *Rectangle) as type *Polygon in assignment

我不能像在 Java 中那样将 Rectangle 实例分配给 Polygon 引用。这背后的原因是什么?

4

1 回答 1

4

问题是您正在考虑将结构嵌入到其他结构中作为继承的能力,但事实并非如此。Go 不是面向对象的,它没有任何类或继承的概念。嵌入的结构语法只是一个很好的简写,它允许一些语法糖。您的代码的 Java 等价物更接近:

class Polygon {
    int sides, area;
}

class Rectangle {
    Polygon p;
    int foo;
}

我假设你想象它相当于:

class Polygon {
    int sides, area;
}

class Rectangle extends Polygon {
    int foo;
}

事实并非如此。

于 2013-08-05T01:14:51.127 回答