Go 编程实例【运行时检查变量类型】

阅读目录

示例

package main

import (
	"fmt"
	"reflect"
)

type Person struct {
    
    
	Name string
	Age  int
}

func typeofObject(variable interface{
    
    }) string {
    
    
	switch variable.(type) {
    
    
	case int:
		return "int"
	case float32:
		return "float32"
	case bool:
		return "boolean"
	case string:
		return "string"
	default:
		// 如果是结构体类型,返回结构体名称
		v := reflect.ValueOf(variable)
		if v.Kind() == reflect.Struct {
    
    
			return v.Type().Name() + " struct{}"
		}
		return "unknown"
	}
}

func main() {
    
    
	var a int = 42
	var b float32 = 3.14
	var c bool = true
	var d string = "hello"
	var e Person = Person{
    
    "John Doe", 30}

	fmt.Println(typeofObject(a)) // Output: int
	fmt.Println(typeofObject(b)) // Output: float32
	fmt.Println(typeofObject(c)) // Output: boolean
	fmt.Println(typeofObject(d)) // Output: string
	fmt.Println(typeofObject(e)) // Output: Person
}
root@debiancc:~/www/test# go run test.go 
int
float32
boolean
string
Person struct{}
root@debiancc:~/www/test# 

示例1

package main

import "fmt"

type Data struct {
    
    
}

func demo2(d Data) {
    
    
	fmt.Println(typeofObject(d))
}

func demo1(v interface{
    
    }) {
    
    
	//断言v为Data类型
	demo2(v.(Data))
}

func main() {
    
    
	//Data类型隐式转换成interface{}类型
	demo1(Data{
    
    })
}

func typeofObject(variable interface{
    
    }) string {
    
    
	switch variable.(type) {
    
    
	case int:
		return "int"
	case float32:
		return "float32"
	case bool:
		return "boolean"
	case string:
		return "string"
	case struct{
    
    }:
		return "struct{}"
	case interface{
    
    }:
		return "interface{}"
	default:
		return "unknown"
	}
}

root@debiancc:~/www/test# go run test.go 
interface{}
root@debiancc:~/www/test# 

猜你喜欢

转载自blog.csdn.net/weiguang102/article/details/130468482