如何从界面获取基础指针类型?
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\n", err, err2 )
fmt.Printf( "as ptr: %+v, as value: %+v", mycarptr, mycarvalue)
}
答案 0 :(得分:0)
答案 1 :(得分:0)
为了能够修改汽车你需要使用指针(就像你已经做过的那样),但为了让其他人(和你自己)更清楚,你应该在指针上定义接口方法:
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)
}
}
我建议您浏览Effective Go,并特别注意Interfaces And Methods部分。