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)
}