type Pet interface { SetName(name string) Name() string Category() string }
type Dog struct { name string }
func(dog *Dog)SetName(name string) { dog.name = name }
func(dog Dog)Name()string { return dog.name }
func(dog Dog)Category()string { return"dog" }
funcTestDog(t *testing.T) { dog := Dog{"little pig"} _, ok := interface{}(dog).(Pet) fmt.Printf("Dog implements interface Pet: %v\n", ok) // Dog implements interface Pet: false _, ok = interface{}(&dog).(Pet) fmt.Printf("*Dog implements interface Pet: %v\n", ok) // *Dog implements interface Pet: true var pet Pet = &dog fmt.Printf("This pet is a %s, the name is %q.\n", pet.Category(), pet.Name()) // This pet is a dog, the name is "little pig".
dog.SetName("monster") fmt.Printf("This pet is a %s, the name is %q.\n", pet.Category(), pet.Name()) // This pet is a dog, the name is "monster". }
空接口
空接口可以表示任何类型
2.通过断言来将空接口转换为制定 // v,ok := p.(int) // ok = true 时转换成功