以下Go代码:
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
我不能将Rectangle实例分配给Polygon引用,就像我在Java中一样。这背后的理由是什么?
答案 0 :(得分:3)
问题在于您正在考虑将结构体嵌入其他结构体中作为继承的能力,而事实并非如此。 Go不是面向对象的,它没有任何类或继承的概念。嵌入式结构语法只是一个很好的简写,允许一些语法糖。代码的Java等价物更紧密:
class Polygon {
int sides, area;
}
class Rectangle {
Polygon p;
int foo;
}
我认为你在想象它相当于:
class Polygon {
int sides, area;
}
class Rectangle extends Polygon {
int foo;
}
情况并非如此。