Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Similar to .net attributes in Go

Tags:

go

What is similar to .net attributes in go lang.

Or how this could be achieved ?

like image 312
Alpha Sierra Avatar asked Mar 20 '23 11:03

Alpha Sierra


1 Answers

Perhaps the most similar mechanism is Struct Tags. Not the most elegant, but they can be evaluated at runtime and provide metadata on struct members.

From the reflect package documentation: type StructTag

They are used, for example, in JSON and XML encoding for custom element names.

For example, using the standard json package, say I have a struct with a field I don't want to appear in my JSON, another field I want to appear only if it is not empty, and a third one I want to refer to with a different name than the struct's internal name. Here's how you specify it with tags:

type Foo struct {
    Bar string `json:"-"` //will not appear in the JSON serialization at all
    Baz string `json:",omitempty"` //will only appear in the json if not empty
    Gaz string `json:"fuzz"` //will appear with the name fuzz, not Gaz
}

I'm using it to document and validate parameters in REST API calls, among other uses.

If you keep the 'optionally space-separated key:"value"' syntax, you can use the Get Method of StructTag to access the values of individual keys, as in the example.

like image 91
Not_a_Golfer Avatar answered Mar 27 '23 15:03

Not_a_Golfer