gorm中模型结构体指针后字符串的意思?

看了下gorm基础,有以下疑问:
定义如下Model

type Model struct {
  ID        uint           `gorm:"primaryKey"`
  CreatedAt time.Time
  UpdatedAt time.Time
  DeletedAt gorm.DeletedAt `gorm:"index"`
}

请问 形如 gorm:"primaryKey" 结构体字段后面的 字符串(gorm称其为 字段标签)是go的语法 (因为我在go结构体一章中未看到这个用法) 还是gorm的语法?

阅读 2.7k
1 个回答

你这问题问的……gorm 就是个库,它还能让你写出不是 golang 语法的东西来?

这东西在语法里叫 Struct Tag(翻译成标签倒也不错)。

我不知道你在哪看的所谓“结构体一章”,但这个东西官方手册在结构体里是有讲过的:

REF: https://go.dev/ref/spec#Struc...

A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. An empty tag string is equivalent to an absent tag. The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored.

struct {
   x, y float64 ""  // an empty tag string is like an absent tag
   name string  "any string is permitted as a tag"
   _    [4]byte "ceci n'est pas un champ de structure"
}

// A struct corresponding to a TimeStamp protocol buffer.
// The tag strings define the protocol buffer field numbers;
// they follow the convention outlined by the reflect package.
struct {
    microsec  uint64 `protobuf:"1"`
    serverIP6 uint64 `protobuf:"2"`

当然这里只是一嘴带过,简单讲了一下。重点篇幅都在反射相关的介绍里:

REF: https://pkg.go.dev/reflect#St...
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题