Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is a really simple example of tags being used with the <a href="http://golang.org/pkg/encoding/json/" rel="noreferrer"><code>encoding/json</code></a> package to control how fields are interpreted during encoding and decoding:</p> <p>Try live: <a href="http://play.golang.org/p/BMeR8p1cKf" rel="noreferrer">http://play.golang.org/p/BMeR8p1cKf</a></p> <pre class="lang-golang prettyprint-override"><code>package main import ( "fmt" "encoding/json" ) type Person struct { FirstName string `json:"first_name"` LastName string `json:"last_name"` MiddleName string `json:"middle_name,omitempty"` } func main() { json_string := ` { "first_name": "John", "last_name": "Smith" }` person := new(Person) json.Unmarshal([]byte(json_string), person) fmt.Println(person) new_json, _ := json.Marshal(person) fmt.Printf("%s\n", new_json) } // *Output* // &amp;{John Smith } // {"first_name":"John","last_name":"Smith"} </code></pre> <p>The json package can look at the tags for the field and be told how to map json &lt;=> struct field, and also extra options like whether it should ignore empty fields when serializing back to json. </p> <p>Basically, any package can use reflection on the fields to look at tag values and act on those values. There is a little more info about them in the reflect package<br> <a href="http://golang.org/pkg/reflect/#StructTag" rel="noreferrer">http://golang.org/pkg/reflect/#StructTag</a> :</p> <blockquote> <p>By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload