What are the use(s) for tags in Go?

前端 未结 3 2075
鱼传尺愫
鱼传尺愫 2020-11-22 01:38

In the Go Language Specification, it mentions a brief overview of tags:

A field declaration may be followed by an optional string literal tag, whic

3条回答
  •  余生分开走
    2020-11-22 02:19

    It's some sort of specifications that specifies how packages treat with a field that is tagged.

    for example:

    type User struct {
        FirstName string `json:"first_name"`
        LastName string `json:"last_name"`
    }
    

    json tag informs json package that marshalled output of following user

    u := User{
            FirstName: "some first name",
            LastName:  "some last name",
        }
    

    would be like this:

    {"first_name":"some first name","last_name":"some last name"}
    

    other example is gorm package tags declares how database migrations must be done:

    type User struct {
      gorm.Model
      Name         string
      Age          sql.NullInt64
      Birthday     *time.Time
      Email        string  `gorm:"type:varchar(100);unique_index"`
      Role         string  `gorm:"size:255"` // set field size to 255
      MemberNumber *string `gorm:"unique;not null"` // set member number to unique and not null
      Num          int     `gorm:"AUTO_INCREMENT"` // set num to auto incrementable
      Address      string  `gorm:"index:addr"` // create index with name `addr` for address
      IgnoreMe     int     `gorm:"-"` // ignore this field
    }
    

    In this example for the field Email with gorm tag we declare that corresponding column in database for the field email must be of type varchar and 100 maximum length and it also must have unique index.

    other example is binding tags that are used very mostly in gin package.

    type Login struct {
        User     string `form:"user" json:"user" xml:"user"  binding:"required"`
        Password string `form:"password" json:"password" xml:"password" binding:"required"`
    }
    
    
    var json Login
    if err := c.ShouldBindJSON(&json); err != nil {
         c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
         return
    }
    

    the binding tag in this example gives hint to gin package that the data sent to API must have user and password fields cause these fields are tagged as required.

    So generraly tags are data that packages require to know how should they treat with data of type different structs and best way to get familiar with the tags a package needs is READING A PACKAGE DOCUMENTATION COMPLETELY.

提交回复
热议问题