【问题标题】:Go : can assign struct to an interface, but not superstructGo:可以将结构分配给接口,但不能分配上层结构
【发布时间】:2013-08-05 15:15:41
【问题描述】:

以下 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 引用。这背后的原理是什么?

【问题讨论】:

  • 它是什么语言?肯定不是 Java。
  • 删除“Java”标签。请用正确的语言标记问题。

标签: inheritance interface go


【解决方案1】:

问题在于您认为将结构嵌入到其他结构中的能力是继承,但事实并非如此。 Go 不是面向对象的,它没有任何类或继承的概念。嵌入的结构语法只是一个很好的简写,它允许一些语法糖。您的代码的 Java 等价物更接近:

class Polygon {
    int sides, area;
}

class Rectangle {
    Polygon p;
    int foo;
}

我假设你想象它相当于:

class Polygon {
    int sides, area;
}

class Rectangle extends Polygon {
    int foo;
}

事实并非如此。

【讨论】:

  • 所以 Go 只支持“has-a”关系,而不支持“is-a”关系?
  • 我想你可以这样说,尽管大多数人都是这样说的。 Go 支持带有字段的结构,这些字段可以是任何有效类型,并且由于结构是有效类型,因此这些字段可以是结构。 “直接在包含的结构上调用方法”模式只是一种方便,而不是真正的语言特性。
  • 是的,np!如果您熟悉 C,Go 结构比 Java 类更接近 C 结构。
猜你喜欢
  • 2018-12-07
  • 2014-03-18
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 2014-06-21
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多