clarkk
clarkk

Reputation: 1

extra value in field in struct golang

What does this "extra" field gorm:"primary_key" do when creating a struct?

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

Upvotes: 0

Views: 380

Answers (2)

evanmcdonnal
evanmcdonnal

Reputation: 48114

Those are what I call 'annotations' they're used by various packages (in this case gorm) to provide more information about how to handle the type. Most commonly you see them on data transfer objects (like json and xml), both packages require them in most use cases.

In this case you're telling gorm this field is a primary key. From a cursory glance at that packages docs it is for relational modeling (like setting up types to map to an rmdb or something of that nature) so it makes sense here to see things like nullable, pk or fk.

Upvotes: 0

Leo Correa
Leo Correa

Reputation: 19829

It's a tag used by the gorm package to let the package know that the field will be used as a primary key

See https://github.com/jinzhu/gorm/blob/b9a39be9c5e77bb0bfebd516114a8a4d605c645a/model_struct.go#L135-L139

gormSettings := parseTagSetting(field.Tag.Get("gorm"))
if _, ok := gormSettings["PRIMARY_KEY"]; ok {
    field.IsPrimaryKey = true
    modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, field)
}

Upvotes: 1

Related Questions