【Go - 如何查看类型,运行前/运行时】

2024-07-27  本文已影响0人  wn777

方式1 - 运行时查看

在Go中,你可以使用reflect.TypeOf()函数来获取变量的类型。这需要导入reflect包。以下是个示例,在运行时打印变量的类型:

package main

import (
    "context"
    "fmt"
    "reflect"

    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

var singlestonMongoClient *mongo.Client = nil

func getSinglestonMongoClient() *mongo.Client {
    if singlestonMongoClient == nil {
        // 创建连接到 MongoDB 的客户端
        // mongodb+srv://xhs:
        uri := "mongodb://localhost:27017"
        client, err := mongo.Connect(context.TODO(), options.Client().
            ApplyURI(uri))

        if err != nil {
            panic(err)
        }
        singlestonMongoClient = client
    }
    return singlestonMongoClient

}
func main() {

    client := getSinglestonMongoClient()
    if client == nil {
        panic("client is nil")
    }

    fmt.Println("c1 %p", client)
    fmt.Printf("Type of client: %v\\n", reflect.TypeOf(client))

}

这段代码会打印出client变量的具体类型,例如*mongo.Client,这表示client是指向mongo.Client类型的指针。

方式2 - 运行前查看

由于Go是强语言类型的,所以运行前,IDE比如VSCode移动到变量上,即可查看类型。

上一篇 下一篇

猜你喜欢

热点阅读