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?
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.