📜  golang typeof (1)

📅  最后修改于: 2023-12-03 15:31:01.132000             🧑  作者: Mango

Golang中的 typeof

在Golang中,没有与C或Java中相似的typeof关键字。但是,可以使用reflect包中的TypeOf()函数来获取一个值的类型。

获取一个变量的类型

使用reflect.TypeOf()函数来获取一个变量的类型。下面是一个例子:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var num float64 = 3.14
    fmt.Printf("Type of num variable is: %v", reflect.TypeOf(num))
}

输出将是:

Type of num variable is: float64
获取一个结构体的类型

可以使用reflect.TypeOf()函数来获取一个结构体的类型。下面是一个例子:

package main

import (
    "fmt"
    "reflect"
)

type person struct {
    name string
    age  int
}

func main() {
    p := person{name: "John", age: 35}
    fmt.Printf("Type of p variable is: %v", reflect.TypeOf(p))
}

输出将是:

Type of p variable is: main.person
使用类型断言动态地获取变量的类型

如果你想动态地判断变量的类型,可以使用类型断言。下面是一个例子:

package main

import (
    "fmt"
)

func printType(i interface{}) {
    switch i.(type) {
    case int:
        fmt.Println("i is an int")
    case float64:
        fmt.Println("i is a float64")
    case string:
        fmt.Println("i is a string")
    default:
        fmt.Println("i is an unknown type")
    }
}

func main() {
    printType(42)
    printType(3.14)
    printType("hello")
    printType(true)
}

输出将是:

i is an int
i is a float64
i is a string
i is an unknown type
总结

虽然Golang没有与C或Java中相似的typeof关键字,但reflect包中的TypeOf()函数具有相似的功能,可以用于获取一个值的类型。类型断言也可以动态地判断变量的类型。