类型判断
在 Go 语言中,有多种方法可以查看一个变量的类型。以下是几种常用的方法:
1. 使用 %T 格式化符
package main
import (
"fmt"
)
func main() {
var x int = 42
fmt.Printf("Type of x is: %T\n", x) //Type of x is: int
}
使用 reflect.TypeOf()
package main
import (
"fmt"
"reflect"
)
func main() {
var y float64 = 3.14
typ := reflect.TypeOf(y)
fmt.Println("Type of y is:", typ.Name()) //Type of y is: float64
}
类型断言和 comma-ok 语法
package main
2
3import (
4 "fmt"
5)
6
7func main() {
8 var z interface{} = "hello"
9 _, ok := z.(string)
10 if ok {
11 fmt.Println("z is of type string")
12 } else {
13 fmt.Println("z is not of type string")
14 }
15}
在调试环境中查看
如果你正在使用集成开发环境(IDE)如 GoLand 或 VS Code,它们通常提供了强大的调试工具。在调试模式下,你可以设置断点,当程序执行到断点处暂停时,直接查看变量窗口或悬停鼠标来查看变量的类型。