golang 查看变量的原始定义类型

更新日期: 2022-05-10 阅读次数: 1994 字数: 352 分类: golang

我想把 golang gin 多语言网站的语言配置提取出来,作为项目的配置项。 而我不知道 language.Chinese 到底是什么类型,是不是 zh 这样的字符串,于是想打印一下输出。

测试一下

package main

import (
	"fmt"
	"reflect"

	"golang.org/x/text/language"
)

func main() {
	fmt.Println("Hello, 世界")
	fmt.Println(language.Chinese)  // zh
	fmt.Println(reflect.TypeOf(language.Chinese))  // language.Tag
	fmt.Println(reflect.TypeOf(language.Chinese).Kind())  // struct
	fmt.Printf("%T\n", language.Chinese)  // language.Tag
}

输出

Hello, 世界
zh
language.Tag
struct
language.Tag

Program exited.

但是,TypeOf 获取到的信息非常有限,帮助不大。还是看源码比较靠谱。

vim-go 插件的 gd 快捷键

For golang, you can use the application godef to do it. The pluging vim-go helps you on setting everything, so, you just type 'gd' in a definition and it goes to the exact definition.

在安装了 vim-go 插件的情况下,在 VIM 中查询变量的定义就方便多了。

直接在变量名上使用快捷键 gd 即可。

返回,ctrl+o 或者 ctrl+t。

例如,通过不断 gd 找到 Tag 的 struct 定义:

package language

type Tag compact.Tag

// String returns the canonical string representation of the language tag.
func (t Tag) String() string {
	return t.tag().String()
}

func (t *Tag) tag() language.Tag {
	return (*compact.Tag)(t).Tag()
}

// Tag returns an internal language Tag version of this tag.
func (t Tag) Tag() language.Tag {
	if t.full != nil {
		return t.full.(language.Tag)
	}
	tag := t.language.Tag()
	if t.language != t.locale {
		loc := t.locale.Tag()
		tag, _ = tag.SetTypeForKey("rg", strings.ToLower(loc.RegionID.String())+"zzzz")
	}
	return tag
}

继续 gd:

package compact

type Tag struct {
	// NOTE: exported tags will become part of the public API.
	language ID
	locale   ID
	full     fullTag // always a language.Tag for now.
}

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式