繁体   English   中英

Go:可以将struct分配给接口,但不能将superstruct

[英]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

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

问题在于您正在考虑将结构嵌入其他结构作为继承的能力,而事实并非如此。 Go不是面向对象的,它没有类或继承的任何概念。 嵌入式struct语法只是一个不错的速记,它允许一些语法糖。 与您的代码等效的Java更紧密:

class Polygon {
    int sides, area;
}

class Rectangle {
    Polygon p;
    int foo;
}

我以为您在想那等于:

class Polygon {
    int sides, area;
}

class Rectangle extends Polygon {
    int foo;
}

事实并非如此。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM