如何获取模型的字段名称和类型?

huangapple go评论67阅读模式
英文:

How to obtain the field names and types of an model?

问题

我正在开发一个自动生成表格和表单的库。

用户传递GORM连接和一个模型列表。

我想知道如何从特定模型中获取字段名称、类型和其他信息。

英文:

I am developing a library to generate tables and forms automatically.

The user passes the GORM connection and a list of models.

I would like to know how to obtain field names, types, and other info from a specific model.

答案1

得分: 1

使用反射包

func FieldNames(models []interface{}) {
	for _, itf := range models {
		model := reflect.TypeOf(itf)
		if model.Kind() == reflect.Struct {
			fieldCnt := model.NumField()
			startIdx := 0
			for startIdx < fieldCnt {
				model.Field(startIdx).Name // 这将给出每个模型中字段的名称
				startIdx += 1
			}
		}
	}
}
英文:

Use the reflect package

func FieldNames(models []interface{})  {
	for _, itf := range models {
		model := reflect.TypeOf(itf)
		if model.Kind() == reflect.Struct{
			fieldCnt := model.NumField()
			startIdx := 0
			for startIdx &lt; fieldCnt {
				model.Field(startIdx).Name //this gives you the name of fields in each model
				startIdx+=1
			}
		}
	}
}

huangapple
  • 本文由 发表于 2022年8月7日 06:00:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/73263548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定