簡體   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