I'm trying to understand what I'm doing wrong here.. all responses appreciated :)
If uncomment "// grow()" works,
else errors:
prog.go:38:2: impossible type switch case: p (type plant) cannot have dynamic type plant1 (grow method has pointer receiver) prog.go:39:16: impossible type assertion: plant1 does not implement plant (grow method has pointer receiver) prog.go:40:2: impossible type switch case: p (type plant) cannot have dynamic type plant2 (grow method has pointer receiver) prog.go:41:16: impossible type assertion: plant2 does not implement plant (grow method has pointer receiver) prog.go:60:12: cannot use p1 (type plant1) as type plant in argument to showHeight: plant1 does not implement plant (grow method has pointer receiver) prog.go:61:12: cannot use p2 (type plant2) as type plant in argument to showHeight: plant2 does not implement plant (grow method has pointer receiver)
https://play.golang.org/p/oMv7LdW85yK
package main
import (
"fmt"
)
type plant1 struct {
name string
height int
}
type plant2 struct {
species string
height int
}
func (self *plant1) grow() {
self.height++
}
func (self *plant2) grow() {
self.height++
}
func (self plant1) getHeight() int {
return self.height
}
func (self plant2) getHeight() int {
return self.height
}
type plant interface {
getHeight() int
//grow()
}
func showHeight(p plant) {
switch p.(type) {
case plant1:
fmt.Println(p.(plant1).name, `Height = `, p.(plant1).getHeight())
case plant2:
fmt.Println(p.(plant2).species, `Height = `, p.(plant2).getHeight())
}
}
func main() {
p1 := plant1{
name: `Plant 10`,
height: 1,
}
p2 := plant2{
species: `Plant 20`,
height: 1,
}
p1.grow()
p1.grow()
p2.grow()
showHeight(p1)
showHeight(p2)
}
The value you wrap into interface isn't addressable. The value have to be addressable to call methods on pointer receivers. The grow methods are declared with pointer receiver. So the compiler sees that plant interface is being implemented neither by plant1 type nor by plant2 type. Thus you can't pass plant1 or plant2 as plant to showHeight func. And the switch is impossible because implementations of plant interface don't include plant1 and plant2 types.
See Why value stored in an interface is not addressable in Golang
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With