package main
import("fmt""reflect")type Person struct{
Name string
Age int}functypeofObject(variable interface{
})string{
switch variable.(type){
caseint:return"int"casefloat32:return"float32"casebool:return"boolean"casestring:return"string"default:// 如果是结构体类型,返回结构体名称
v := reflect.ValueOf(variable)if v.Kind()== reflect.Struct {
return v.Type().Name()+" struct{}"}return"unknown"}}funcmain(){
var a int=42var b float32=3.14var c bool=truevar 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{
}funcdemo2(d Data){
fmt.Println(typeofObject(d))}funcdemo1(v interface{
}){
//断言v为Data类型demo2(v.(Data))}funcmain(){
//Data类型隐式转换成interface{}类型demo1(Data{
})}functypeofObject(variable interface{
})string{
switch variable.(type){
caseint:return"int"casefloat32:return"float32"casebool:return"boolean"casestring:return"string"casestruct{
}:return"struct{}"caseinterface{
}:return"interface{}"default:return"unknown"}}
root@debiancc:~/www/test# go run test.go
interface{}
root@debiancc:~/www/test#