type Person interface { Run() //只要有run方法的都算 Person結構體 } //還有定義方法 type Person2 interface { Speak() Person //至關於run() }
package main import "fmt" type Person interface { Run() } type Person2 struct { name string } func (P Person2)Run(){ fmt.Println("我會走") } type Person3 struct { name string } func (P Person3)Run(){ fmt.Println("我會飛") } func test(p Person){ p.Run() } func main() { p1 :=Person2{} p2 :=Person3{} test(p1) test(p2) } //p1與p2都有Run方法都算Person結構體,全部均可以由Run方法
interface {} //能夠接受全部數據類型 package main import "fmt" func Test(a interface{}){fmt.Println(a)} func main(){ Test(1) Test("WWW") }
寫法一:code
package main import "fmt" type Person struct { name string } func Test(a interface{}){ _,err :=a.(*Person) if !err{ fmt.Println("是Person") } } func main(){ a := Person{name: "p1"} Test(a) }
寫法二:對象
package main import ( "fmt" ) type Person struct { name string } func Test(a interface{}) { switch a.(type) { //若是要獲取a的對象就AStruct :=a.(type) case Person: fmt.Println("是Person") default: fmt.Println("不是Person") } } func main() { a := Person{name: "p1"} Test(a) }