多态
参数是interface 只能是指针类型
package polymorphic
import (
"fmt"
"testing"
)
type code string
type Programmer interface {
WriteHelloWolrd() code
}
type GoProgrammer struct {
}
type JavaProgrammer struct {
}
func (p *GoProgrammer) WriteHelloWolrd() code{
return "fmt.Println(\"Hello world\")"
}
func (p *JavaProgrammer) WriteHelloWolrd() code{
return "fmt.Println(\"Hello world\")"
}
//指针类型
func writeFirstProgrammer(p Programmer){
//%T输出类型
fmt.Printf("%T %v\n",p,p.WriteHelloWolrd())
}
func TestPolymorphism(t *testing.T){
goProg := new(GoProgrammer)
JavaProg := new(JavaProgrammer)
writeFirstProgrammer(goProg)
writeFirstProgrammer(JavaProg)
}
空接口与断言
- 空接口可以表示任何类型
- 通过断言来将空接口转换为指定类型
v,ok := p.(int) //ok=true 时转换成功
package empty_interface
import (
"fmt"
"testing"
)
func DoSomeThing(p interface{}){
//if i,ok := p.(int);ok{
// fmt.Printf("Int %d",i)
// return
//}
//if i,ok := p.(string);ok{
// fmt.Printf("String %s",i)
// return
//}
switch v := p.(type) {
case int:
fmt.Println("int", v)
case string:
fmt.Println("string", v)
default:
fmt.Println("unknow")
}
//fmt.Println("Unkown")
}
func TestCheck(t *testing.T){
DoSomeThing(10)
}