go空接口

空接口或者最小接口 不包含任何方法,它对实现不做任何要求:

type Any interface {}

可以赋任何类型的值。

package main 

import "fmt"

var a = 5  
var str1 string = "Hello"

type Person struct{
	name string
	age int
}

type Any interface{}

func main(){
	var a1 Any
    a1  = 5
    fmt.Printf("the value of a1 is %v\n",a1)

    a1  = str1
    fmt.Printf("the value of a1 is %v\n",a1)

    p :=&Person{"Mike",15}
    a1  = p
    fmt.Printf("the value of a1 is %v\n",a1)

    switch t := a1.(type){
    case int:
		fmt.Printf("Type int %T\n",t)
	case string:
		fmt.Printf("Type string %T\n",t)
	case *Person:
		fmt.Printf("Type Person %T\n",t)
	default:
		fmt.Printf("Type unknow %T\n",t)
    }
 }

在上面的例子中,接口变量a被依次赋予一个int , string ,Person实例的值 type-swtich来测试它的实际类型。每个interface {}变量在内存中占据两个字长:一个用来存储它包含的类型,另一个用来存储它包含的数据或者指向数据的指针。

发布了123 篇原创文章 · 获赞 71 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/boke14122621/article/details/99410372
今日推荐