Go语言中可以将结构体赋值给接口,但不能将超级结构体赋值给接口。

huangapple go评论81阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2013年8月5日 09:03:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/18049281.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定