tldr
tldr

Reputation: 12112

Go : can assign struct to an interface, but not 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?

Upvotes: 0

Views: 175

Answers (1)

joshlf
joshlf

Reputation: 23537

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.

Upvotes: 4

Related Questions