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.

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

报告相同问题?