dpbl91234 2013-08-05 01:03
浏览 43
已采纳

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

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条回答 默认 最新

  • doushou8299 2013-08-05 01:14
    关注

    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:

    class Polygon {
        int sides, area;
    }
    
    class Rectangle {
        Polygon p;
        int foo;
    }
    

    I assume you were imagining that it was equivalent to:

    class Polygon {
        int sides, area;
    }
    
    class Rectangle extends Polygon {
        int foo;
    }
    

    which is not the case.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥88 实在没有想法,需要个思路
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)