go 接口类型

package main

import "fmt"

func test1() {
	var a interface{}  // 空接口可以实现任何类型的变量
	var b int =100 
	a = b
	fmt.Printf("test1 00> %T %v \n",a,a)
	
	var c string =  "hello"
	a = c
	fmt.Printf("test1 01> %T %v \n",a,a)

	var d map[string]int = make(map[string]int,100)
	d["abc"] = 100
	d["eke"] = 30
	a = d
	fmt.Printf("test1 02> %T %v \n",a,a)
}

func describe(i interface{}){
	fmt.Printf("Type =%T, value=%v\n",i,i)
}

func test2() {
	s := "Hello World"
	describe(s)
	i := 55
	describe(i)
	strt := struct{
		name string
	}{
		name : "Naveen R",
	}
	describe(strt)
}


func findType(i interface{}) {
	switch i.(type) {
	case string:
		fmt . Printf("I am a string and my value is %s\n", i.(string))
	case int:
		fmt. Printf("I am an int and my value is %d\n", i.(int))
	default:
		fmt. Printf( "Unknown type\n" )
	}}



//接口类型的变量就是一个容器,该容器能存放任何实现了该接口方法的对象实例
func main() {
	test1()
	test2()
	findType("hello")
	findType(77)
	findType(89.98)
	
	
}

输出:

test1 00> int 100
test1 01> string hello
test1 02> map[string]int map[abc:100 eke:30]
Type =string, value=Hello World
Type =int, value=55
Type =struct { name string }, value={Naveen R}
I am a string and my value is hello
I am an int and my value is 77
Unknown type
posted @ 2022-03-18 19:24  ty1539  阅读(49)  评论(0编辑  收藏  举报