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

方式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移动到变量上,即可查看类型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值