Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is metadata or attributes allowed in Golang?

Tags:

validation

go

How are these various validation libraries adding this meta data to structs like:

type Post struct {
    Title    string `valid:"alphanum,required"`
    Message  string `valid:"duck,ascii"`
    AuthorIP string `valid:"ipv4"`
    Date     string `valid:"-"`
}

I'm confused, the property is Title, the type is string. Beyond that how can you just add valid:"alphanum,required" Is this using reflection?

Is this like attributes in other languages?

[Required]
public int Title { get;set; }
like image 711
cool breeze Avatar asked Feb 04 '16 15:02

cool breeze


People also ask

What are metadata attributes?

The metadata attributes express qualifications on the content. These qualifications can be used to modify the processing of the content. One typical use of the metadata attributes is to filter content based on their values.

What are tags in golang?

In Golang, we use Tags as metadata to provide for each field in a struct. This information is made available using reflection. This is typically used by packages that transform data from one form to another. For example, we can use Tags to encode/decode JSON data or read and write from a DB.


1 Answers

Go doesn't have attributes in general sense. The strings in the struct are struct tags:

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. The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored.

// A struct corresponding to the TimeStamp protocol buffer.
// The tag strings define the protocol buffer field numbers.
struct {
    microsec  uint64 "field 1"
    serverIP6 uint64 "field 2"
    process   string "field 3"
}

You can't add or change them, but you can access them using the reflect package.

Another thing that kinda looks like attributes are "magic comments" like

// +build amd64

or

//go:noinline

These are compiler-specific and IIRC are not a part of the language specification.

like image 137
Ainar-G Avatar answered Sep 23 '22 16:09

Ainar-G