How do I get the underlying pointer type from an interface?
package main
import (
"fmt"
)
type Car interface {
Drive() string
}
type MyCar struct {
name string
}
func (MyCar) Drive ( ) string {
return "rum rum"
}
func main() {
var car Car
mycar := &MyCar{name:"mycar"}
car = mycar
mycarptr, err := car.(*MyCar)
mycarvalue, err2 := car.(MyCar)
fmt.Printf( "as ptr failed: %t, as value failed: %t
", err, err2 )
fmt.Printf( "as ptr: %+v, as value: %+v", mycarptr, mycarvalue)
}
Your first assertion to *MyCar works fine
Here is a playground example to illustrate
Your second assertion to MyCar will fail since it's not a pointer.
To be able to modify the car you need to use a pointer to it (like you already did), however to make it more clear to others (and yourself) you should define the interface method on the pointer:
type Drivable interface {
Drive() string
}
type Car struct {
name string
}
func (*Car) Drive() string {
return "rum rum"
}
type SpaceShip struct {
name string
}
func (*SpaceShip) Drive() string {
return "sound spaceships makes when you drive / fly them"
}
func Drive(d Drivable) {
switch d := d.(type) { // d now is the actual type
case *Car:
fmt.Println("Got a car named", d.name)
case *SpaceShip:
fmt.Println("Got a spaceship named", d.name)
}
}
I recommend going through Effective Go, and pay extra attention to the Interfaces And Methods section.