package main import ( "fmt" ) func myFunc(abx interface{}){ fmt.Println("my func is called") fmt.Println(abx)//这个abx 可以随便换 //类型断言机制 value,ok:=abx.(string) if !ok{ fmt.Println("abx is not string") }else{ fmt.Println("abx is string,value=",value) } } type Student struct { name string } func main() { //反射,每个变量可以看做为pair<type,value>,能够通过变量反射找到type和value stu:=Student{"jiaqiang"} myFunc(stu) myFunc(100) myFunc(31.4) //cc pair<type Book,value:Book的地址 > cc:=&Book{} var r Reader //r pair<type:,value:> r=cc r.ReadBook()//实际是调用的pair<Book>中的方法 var w Writer w=r.(Writer)//此处断言成功了,因为r和w的type一致 w.WriteBook() } type Reader interface { ReadBook() } type Writer interface{ WriteBook() } type Book struct{//这个是Book 类 } func (this *Book) ReadBook(){ fmt.Println("Read a book") } func (this *Book) WriteBook() { fmt.Println("Write a book") }
go语言的pair
最新推荐文章于 2024-01-10 17:34:21 发布