What does a record of this kind, or rather, why indicate the text in the type of int and how to get this text?
type User struct { Age int `gorm:"size:255"` } fmt.Println(User{}) // {0} What does a record of this kind, or rather, why indicate the text in the type of int and how to get this text?
type User struct { Age int `gorm:"size:255"` } fmt.Println(User{}) // {0} This is a label , it can hold metadata for the field. In this particular case, it is a label for gorm (ORM such) about the data type of this field in the database .
They represent a set of pairs of a ключ:"значение" separated by spaces , surrounded by backward quotes ( `метаданные` ), like a JSON object, only simpler: only string keys and string values. More example:
`foo:"bar" baz:"quux"` Access to such tags is made through reflection, here is an example ( from here ):
package main import ( "fmt" "reflect" ) func main() { type User struct { Name string `mytag:"MyName"` Email string `mytag:"MyEmail"` } u := User{"Bob", "bob@mycompany.com"} t := reflect.TypeOf(u) for _, fieldName := range []string{"Name", "Email"} { field, found := t.FieldByName(fieldName) if !found { continue } fmt.Printf("\nField: User.%s\n", fieldName) fmt.Printf("\tWhole tag value : %q\n", field.Tag) fmt.Printf("\tValue of 'mytag': %q\n", field.Tag.Get("mytag")) } } Field: User.Name Whole tag value : "mytag:\"MyName\"" Value of 'mytag': "MyName" Field: User.Email Whole tag value : "mytag:\"MyEmail\"" Value of 'mytag': "MyEmail" Source: https://ru.stackoverflow.com/questions/563445/
All Articles