英文:
Go : can assign struct to an interface, but not superstruct
问题
以下是翻译好的内容:
以下是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中那样。这背后的原理是什么?
英文:
The following Go code:
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)
}
causes this error:
cannot use new(Rectangle) (type *Rectangle) as type *Polygon in assignment
I can't assign a Rectangle instance to a Polygon reference, like I can in Java. What is the rationale behind this?
答案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;
}
但实际情况并非如此。
英文:
The problem is that you're thinking of the ability to embed structs in other structs as inheritance, which it is not. Go is not object-oriented, and it doesn't have any concept of classes or inheritance. The embedded struct syntax is just a nice shorthand that allows for some syntactic sugar. The Java equivalent of your code is more closely:
<!-- language: lang-java -->
class Polygon {
int sides, area;
}
class Rectangle {
Polygon p;
int foo;
}
I assume you were imagining that it was equivalent to:
<!-- language: lang-java -->
class Polygon {
int sides, area;
}
class Rectangle extends Polygon {
int foo;
}
which is not the case.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论