1658896860
In questo tutorial imparerai come utilizzare i tag struct (strutture) in Go (Golang). I tag Go struct sono annotazioni che appaiono dopo il tipo in una dichiarazione Go struct.
Le strutture , o struct , vengono utilizzate per raccogliere più informazioni insieme in un'unica unità. Queste raccolte di informazioni vengono utilizzate per descrivere concetti di livello superiore, ad esempio Address
composto da a Street
, City
, State
e PostalCode
. Quando leggi queste informazioni da sistemi come database o API, puoi utilizzare i tag struct per controllare come queste informazioni vengono assegnate ai campi di uno struct. I tag struct sono piccoli frammenti di metadati allegati ai campi di uno struct che forniscono istruzioni ad altro codice Go che funziona con lo struct.
I tag Go struct sono annotazioni che appaiono dopo il tipo in una dichiarazione Go struct. Ogni tag è composto da brevi stringhe associate a un valore corrispondente.
Un tag struct si presenta così, con il tag sfalsato con i `
caratteri backtick:
type User struct {
Name string `example:"name"`
}
Altro codice Go è quindi in grado di esaminare queste strutture ed estrarre i valori assegnati a chiavi specifiche richieste. I tag struct non hanno alcun effetto sul funzionamento del codice senza codice aggiuntivo che li esamini.
Prova questo esempio per vedere che aspetto hanno i tag struct e che senza il codice di un altro pacchetto non avranno alcun effetto.
package main
import "fmt"
type User struct {
Name string `example:"name"`
}
func (u *User) String() string {
return fmt.Sprintf("Hi! My name is %s", u.Name)
}
func main() {
u := &User{
Name: "Sammy",
}
fmt.Println(u)
}
Questo produrrà:
Output
Hi! My name is Sammy
Questo esempio definisce un User
tipo con un Name
campo. Al Name
campo è stato assegnato un tag struct di example:"name"
. Ci riferiremo a questo tag specifico nella conversazione come "tag struct esempio" perché utilizza la parola "esempio" come chiave. Il example
tag struct ha il valore "name"
per il Name
campo. Sul User
tipo, definiamo anche il String()
metodo richiesto fmt.Stringer
dall'interfaccia. Questo verrà chiamato automaticamente quando passiamo il tipo fmt.Println
e ci darà la possibilità di produrre una versione ben formattata della nostra struttura.
All'interno del corpo di main
, creiamo una nuova istanza del nostro User
tipo e la passiamo a fmt.Println
. Anche se lo struct aveva un tag struct presente, vediamo che non ha alcun effetto sul funzionamento di questo codice Go. Si comporterà esattamente allo stesso modo se il tag struct non fosse presente.
Per utilizzare i tag struct per ottenere qualcosa, è necessario scrivere altro codice Go per esaminare gli struct in fase di esecuzione. La libreria standard ha pacchetti che utilizzano tag struct come parte della loro operazione. Il più popolare di questi è il encoding/json
pacchetto.
JavaScript Object Notation (JSON) è un formato testuale per la codifica di raccolte di dati organizzate in chiavi di stringa diverse. È comunemente usato per comunicare dati tra diversi programmi poiché il formato è abbastanza semplice che esistono librerie per decodificarlo in molti linguaggi diversi. Quello che segue è un esempio di JSON:
{
"language": "Go",
"mascot": "Gopher"
}
Questo oggetto JSON contiene due chiavi language
e mascot
. Dopo queste chiavi ci sono i valori associati. Qui la language
chiave ha un valore Go
e mascot
gli viene assegnato il valore Gopher
.
Il codificatore JSON nella libreria standard utilizza i tag struct come annotazioni che indicano al codificatore come vorresti nominare i tuoi campi nell'output JSON. Questi meccanismi di codifica e decodifica JSON possono essere trovati nel encoding/json
pacchetto .
Prova questo esempio per vedere come viene codificato JSON senza tag struct:
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
)
type User struct {
Name string
Password string
PreferredFish []string
CreatedAt time.Time
}
func main() {
u := &User{
Name: "Sammy the Shark",
Password: "fisharegreat",
CreatedAt: time.Now(),
}
out, err := json.MarshalIndent(u, "", " ")
if err != nil {
log.Println(err)
os.Exit(1)
}
fmt.Println(string(out))
}
Questo stamperà il seguente output:
Output
{
"Name": "Sammy the Shark",
"Password": "fisharegreat",
"CreatedAt": "2019-09-23T15:50:01.203059-04:00"
}
Abbiamo definito una struttura che descrive un utente con campi che includono il nome, la password e l'ora in cui l'utente è stato creato. All'interno della main
funzione, creiamo un'istanza di questo utente fornendo valori per tutti i campi tranne PreferredFish
(a Sammy piacciono tutti i pesci). Abbiamo quindi passato l'istanza di User
alla json.MarshalIndent
funzione. Viene utilizzato in modo da poter vedere più facilmente l'output JSON senza utilizzare uno strumento di formattazione esterno. Questa chiamata potrebbe essere sostituita con json.Marshal(u)
per stampare JSON senza spazi bianchi aggiuntivi. I due argomenti aggiuntivi per json.MarshalIndent
controllare il prefisso dell'output (che abbiamo omesso con la stringa vuota) ei caratteri da utilizzare per il rientro, che qui sono due caratteri spazio. Eventuali errori prodotti da json.MarshalIndent
vengono registrati e il programma termina utilizzandoos.Exit(1)
. Infine, abbiamo eseguito il cast di []byte
restituito da json.MarshalIndent
a string
e passato la stringa risultante fmt.Println
per la stampa sul terminale.
I campi della struttura appaiono esattamente come denominati. Questo non è il tipico stile JSON che potresti aspettarti, tuttavia, che utilizza l'involucro del cammello per i nomi dei campi. In questo prossimo esempio cambierai i nomi del campo per seguire lo stile della cassa del cammello. Come vedrai quando esegui questo esempio, questo non funzionerà perché i nomi dei campi desiderati sono in conflitto con le regole di Go sui nomi dei campi esportati.
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
)
type User struct {
name string
password string
preferredFish []string
createdAt time.Time
}
func main() {
u := &User{
name: "Sammy the Shark",
password: "fisharegreat",
createdAt: time.Now(),
}
out, err := json.MarshalIndent(u, "", " ")
if err != nil {
log.Println(err)
os.Exit(1)
}
fmt.Println(string(out))
}
Questo presenterà il seguente output:
Output
{}
In questa versione, abbiamo modificato i nomi dei campi per essere rivestiti di cammello. Ora Name
è name
, Password
è password
e finalmente CreatedAt
è createdAt
. All'interno del corpo di main
abbiamo cambiato l'istanza della nostra struttura per usare questi nuovi nomi. Passiamo quindi la struttura alla json.MarshalIndent
funzione come prima. L'output, questa volta è un oggetto JSON vuoto, {}
.
I campi Camel Casella richiedono correttamente che il primo carattere sia minuscolo. Sebbene a JSON non importi come denomini i tuoi campi, Go sì, poiché indica la visibilità del campo al di fuori del pacchetto. Poiché il encoding/json
pacchetto è un pacchetto separato dal main
pacchetto che stiamo utilizzando, dobbiamo maiuscolo il primo carattere per renderlo visibile a encoding/json
. Sembrerebbe che siamo a un punto morto. Abbiamo bisogno di un modo per trasmettere al codificatore JSON come vorremmo fosse chiamato questo campo.
È possibile modificare l'esempio precedente per esportare i campi correttamente codificati con nomi di campo con maiuscole di cammello annotando ogni campo con un tag struct. Il tag struct che encoding/json
riconosce ha una chiave json
e un valore che controlla l'output. Inserendo la versione con custodia in cammello dei nomi dei campi come valore della json
chiave, il codificatore utilizzerà invece quel nome. Questo esempio risolve i due tentativi precedenti:
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
)
type User struct {
Name string `json:"name"`
Password string `json:"password"`
PreferredFish []string `json:"preferredFish"`
CreatedAt time.Time `json:"createdAt"`
}
func main() {
u := &User{
Name: "Sammy the Shark",
Password: "fisharegreat",
CreatedAt: time.Now(),
}
out, err := json.MarshalIndent(u, "", " ")
if err != nil {
log.Println(err)
os.Exit(1)
}
fmt.Println(string(out))
}
Questo produrrà:
Output
{
"name": "Sammy the Shark",
"password": "fisharegreat",
"preferredFish": null,
"createdAt": "2019-09-23T18:16:17.57739-04:00"
}
Abbiamo cambiato i campi struct per renderli visibili ad altri pacchetti mettendo in maiuscolo le prime lettere dei loro nomi. Tuttavia, questa volta abbiamo aggiunto tag struct sotto forma di json:"name"
, dov'era "name"
il nome che volevamo json.MarshalIndent
usare durante la stampa del nostro struct come JSON.
Ora abbiamo formattato correttamente il nostro JSON. Si noti, tuttavia, che i campi per alcuni valori sono stati stampati anche se non sono stati impostati quei valori. Il codificatore JSON può eliminare anche questi campi, se lo desideri.
È comune sopprimere l'output dei campi non impostati in JSON. Poiché tutti i tipi in Go hanno un "valore zero", un valore predefinito su cui sono impostati, il encoding/json
pacchetto necessita di informazioni aggiuntive per poter dire che alcuni campi dovrebbero essere considerati non impostati quando assume questo valore zero. All'interno della parte del valore di qualsiasi json
tag struct, puoi suffissare il nome desiderato del tuo campo con ,omitempty
per indicare al codificatore JSON di sopprimere l'output di questo campo quando il campo è impostato sul valore zero. L'esempio seguente corregge gli esempi precedenti in modo che non restituiscano più campi vuoti:
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
)
type User struct {
Name string `json:"name"`
Password string `json:"password"`
PreferredFish []string `json:"preferredFish,omitempty"`
CreatedAt time.Time `json:"createdAt"`
}
func main() {
u := &User{
Name: "Sammy the Shark",
Password: "fisharegreat",
CreatedAt: time.Now(),
}
out, err := json.MarshalIndent(u, "", " ")
if err != nil {
log.Println(err)
os.Exit(1)
}
fmt.Println(string(out))
}
Questo esempio produrrà:
Output
{
"name": "Sammy the Shark",
"password": "fisharegreat",
"createdAt": "2019-09-23T18:21:53.863846-04:00"
}
Abbiamo modificato gli esempi precedenti in modo che il PreferredFish
campo abbia ora il tag struct json:"preferredFish,omitempty"
. La presenza ,omitempty
dell'aumento fa sì che l'encoder JSON salti quel campo, poiché abbiamo deciso di lasciarlo non impostato. Questo aveva il valore null
negli output dei nostri esempi precedenti.
Questo output ha un aspetto molto migliore, ma stiamo ancora stampando la password dell'utente. Il encoding/json
pacchetto fornisce un altro modo per ignorare completamente i campi privati.
Alcuni campi devono essere esportati da struct in modo che altri pacchetti possano interagire correttamente con il tipo. Tuttavia, la natura di questi campi può essere sensibile, quindi in queste circostanze vorremmo che il codificatore JSON ignori completamente il campo, anche quando è impostato. Questo viene fatto usando il valore speciale -
come argomento del valore per un json:
tag struct.
Questo esempio risolve il problema dell'esposizione della password dell'utente.
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
)
type User struct {
Name string `json:"name"`
Password string `json:"-"`
CreatedAt time.Time `json:"createdAt"`
}
func main() {
u := &User{
Name: "Sammy the Shark",
Password: "fisharegreat",
CreatedAt: time.Now(),
}
out, err := json.MarshalIndent(u, "", " ")
if err != nil {
log.Println(err)
os.Exit(1)
}
fmt.Println(string(out))
}
Quando esegui questo esempio, vedrai questo output:
Output
{
"name": "Sammy the Shark",
"createdAt": "2019-09-23T16:08:21.124481-04:00"
}
L'unica cosa che abbiamo cambiato in questo esempio rispetto ai precedenti è che il campo password ora usa il "-"
valore speciale per il suo json:
tag struct. Nell'output di questo esempio che il password
campo non è più presente.
Queste caratteristiche del encoding/json
pacchetto — ,omitempty
, "-"
, e altre opzioni — non sono standard. Ciò che un pacchetto decide di fare con i valori di un tag struct dipende dalla sua implementazione. Poiché il encoding/json
pacchetto fa parte della libreria standard, anche altri pacchetti hanno implementato queste funzionalità allo stesso modo per una questione di convenzione. Tuttavia, è importante leggere la documentazione per qualsiasi pacchetto di terze parti che utilizza tag struct per sapere cosa è supportato e cosa no.
I tag struct offrono un potente mezzo per aumentare la funzionalità del codice che funziona con i tuoi struct. Molte librerie standard e pacchetti di terze parti offrono modi per personalizzare il loro funzionamento attraverso l'uso di tag struct. Il loro utilizzo efficace nel codice fornisce questo comportamento di personalizzazione e documenta in modo succinto come questi campi vengono utilizzati per gli sviluppatori futuri.
Fonte dell'articolo originale su https://www.digitalocean.com
#go #golang
1650364405
Pick the right hash tags and enjoy likes and comments on the post.
Making engaging reels about the travels, fashion, fitness, contest, and more, the results are not satisfactory. All you get is a few likes, comments and nothing else. You need the engagement on your post to bring more business to you. How can you bring interaction to the content? Indeed you can buy real instagram likes uk to get high rates. But how can you make the Instagram world hit the likes button under the post? You need to boost the reach. You must present your content to the right audiences to get higher interaction rates.
Your Instagram #tags are the power tool that works like magic for influencers and businesses. The blue text with # is the magical option that increases the viability of the posts. The Instagram algorithm keeps on changing, and now the engagement on the post is a must to place the content at a higher place in followers’ feed. For this, you require more likes and comments under the post. For this, you must lift the reach by using perfect tags.
Why are hashtags popular on Instagram?
Let me clear it for you. Do you know how many active users this digital handle has? It is about 2B and more, and the count is changing every day. Each of the followers must be posting something on the handles. Thousands of profit must be of a similar niche as yours. If you are the business and running the clothing brands, then many other companies deal with clothes. So, customers or followers have many choices to choose from. Why would they follow you or purchase from your companies?
Your reply must be that you offer quality material at the best rates. But how does anyone finds out about you? Indeed you can buy active instagram followers uk to bring more fans, but how can you boost the reach of your voices. All businesses must represent their product to the right audiences, but how?
Of course, hashtags.
Table of Contents
There are some basic tags that you can use, but if you are more specific about your approach, choose the relevant tags for your business. Your #tags game must be industry oriented. So in this part, you will learn about the famous tags as per various niches.
Tags for Travel Niche
Indeed this niche is famous on Instagram, and influencers earn handsome amounts. These #tags are best for you if you possess a similar place. Use them smartly and rightly!
#TravelPhotography
#PicOfTheDay
#NaturePhotography
#TravelBlogger
#beautiful
#landscape
#adventure
#explore
#instatravel
#photo
#trip
#summer
#travelgram
#photography
#art
#travel
#wanderlust
#nature
#instagood
#PhotoOfTheDay
After thee travel next most famous niche is fashion. You can earn handsome amount form it. But for this you need to pick the right tags form the following:
So, what to boost your fitness business then uses these tags and enjoys likes:
Best Tags for Giveaway
So, are you arranging the giveaway and want a maximum number of people to participate? If so, then it is time to boost the reach vis using these tags
Are you the reels queen, or do you want to become the one? Then these below mentioned tags are for you. But don’t go for all of them because you can use only thirty of them. Pick it smartly!
Do you love to eat and what to share your experience with another foodie on Instagram? If you are visiting any cafe, then before uploading, always add one of the following tags!
There is a long list of each niche, and you can use all of them. If you are confused about what to pick and whatnot, here is the guide to choosing the perfect tag.
Study your competition. Review their post and study the tags they are using.
1599854400
Go announced Go 1.15 version on 11 Aug 2020. Highlighted updates and features include Substantial improvements to the Go linker, Improved allocation for small objects at high core counts, X.509 CommonName deprecation, GOPROXY supports skipping proxies that return errors, New embedded tzdata package, Several Core Library improvements and more.
As Go promise for maintaining backward compatibility. After upgrading to the latest Go 1.15 version, almost all existing Golang applications or programs continue to compile and run as older Golang version.
#go #golang #go 1.15 #go features #go improvement #go package #go new features
1599298740
Golang Structs are the user-defined type that contains the collection of named fields/properties. It is used to group related data to form a single unit. Any real-world entity that has the set of properties can be represented using a struct.
Structs are useful for grouping data together to create records.
If you’re coming from the object-oriented programming background, you can think of a struct as the lightweight class that supports the composition but not an inheritance.
Go struct is a user-defined type that represents the collection of fields.
It can be used in the places where it makes sense to group data into the single unit rather than maintaining each of them as the separate types.
For instance, a student has firstName, lastName, and age. It makes sense to group these three fields into a single structure student.
#golang #golang structs #go
1658896860
In questo tutorial imparerai come utilizzare i tag struct (strutture) in Go (Golang). I tag Go struct sono annotazioni che appaiono dopo il tipo in una dichiarazione Go struct.
Le strutture , o struct , vengono utilizzate per raccogliere più informazioni insieme in un'unica unità. Queste raccolte di informazioni vengono utilizzate per descrivere concetti di livello superiore, ad esempio Address
composto da a Street
, City
, State
e PostalCode
. Quando leggi queste informazioni da sistemi come database o API, puoi utilizzare i tag struct per controllare come queste informazioni vengono assegnate ai campi di uno struct. I tag struct sono piccoli frammenti di metadati allegati ai campi di uno struct che forniscono istruzioni ad altro codice Go che funziona con lo struct.
I tag Go struct sono annotazioni che appaiono dopo il tipo in una dichiarazione Go struct. Ogni tag è composto da brevi stringhe associate a un valore corrispondente.
Un tag struct si presenta così, con il tag sfalsato con i `
caratteri backtick:
type User struct {
Name string `example:"name"`
}
Altro codice Go è quindi in grado di esaminare queste strutture ed estrarre i valori assegnati a chiavi specifiche richieste. I tag struct non hanno alcun effetto sul funzionamento del codice senza codice aggiuntivo che li esamini.
Prova questo esempio per vedere che aspetto hanno i tag struct e che senza il codice di un altro pacchetto non avranno alcun effetto.
package main
import "fmt"
type User struct {
Name string `example:"name"`
}
func (u *User) String() string {
return fmt.Sprintf("Hi! My name is %s", u.Name)
}
func main() {
u := &User{
Name: "Sammy",
}
fmt.Println(u)
}
Questo produrrà:
Output
Hi! My name is Sammy
Questo esempio definisce un User
tipo con un Name
campo. Al Name
campo è stato assegnato un tag struct di example:"name"
. Ci riferiremo a questo tag specifico nella conversazione come "tag struct esempio" perché utilizza la parola "esempio" come chiave. Il example
tag struct ha il valore "name"
per il Name
campo. Sul User
tipo, definiamo anche il String()
metodo richiesto fmt.Stringer
dall'interfaccia. Questo verrà chiamato automaticamente quando passiamo il tipo fmt.Println
e ci darà la possibilità di produrre una versione ben formattata della nostra struttura.
All'interno del corpo di main
, creiamo una nuova istanza del nostro User
tipo e la passiamo a fmt.Println
. Anche se lo struct aveva un tag struct presente, vediamo che non ha alcun effetto sul funzionamento di questo codice Go. Si comporterà esattamente allo stesso modo se il tag struct non fosse presente.
Per utilizzare i tag struct per ottenere qualcosa, è necessario scrivere altro codice Go per esaminare gli struct in fase di esecuzione. La libreria standard ha pacchetti che utilizzano tag struct come parte della loro operazione. Il più popolare di questi è il encoding/json
pacchetto.
JavaScript Object Notation (JSON) è un formato testuale per la codifica di raccolte di dati organizzate in chiavi di stringa diverse. È comunemente usato per comunicare dati tra diversi programmi poiché il formato è abbastanza semplice che esistono librerie per decodificarlo in molti linguaggi diversi. Quello che segue è un esempio di JSON:
{
"language": "Go",
"mascot": "Gopher"
}
Questo oggetto JSON contiene due chiavi language
e mascot
. Dopo queste chiavi ci sono i valori associati. Qui la language
chiave ha un valore Go
e mascot
gli viene assegnato il valore Gopher
.
Il codificatore JSON nella libreria standard utilizza i tag struct come annotazioni che indicano al codificatore come vorresti nominare i tuoi campi nell'output JSON. Questi meccanismi di codifica e decodifica JSON possono essere trovati nel encoding/json
pacchetto .
Prova questo esempio per vedere come viene codificato JSON senza tag struct:
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
)
type User struct {
Name string
Password string
PreferredFish []string
CreatedAt time.Time
}
func main() {
u := &User{
Name: "Sammy the Shark",
Password: "fisharegreat",
CreatedAt: time.Now(),
}
out, err := json.MarshalIndent(u, "", " ")
if err != nil {
log.Println(err)
os.Exit(1)
}
fmt.Println(string(out))
}
Questo stamperà il seguente output:
Output
{
"Name": "Sammy the Shark",
"Password": "fisharegreat",
"CreatedAt": "2019-09-23T15:50:01.203059-04:00"
}
Abbiamo definito una struttura che descrive un utente con campi che includono il nome, la password e l'ora in cui l'utente è stato creato. All'interno della main
funzione, creiamo un'istanza di questo utente fornendo valori per tutti i campi tranne PreferredFish
(a Sammy piacciono tutti i pesci). Abbiamo quindi passato l'istanza di User
alla json.MarshalIndent
funzione. Viene utilizzato in modo da poter vedere più facilmente l'output JSON senza utilizzare uno strumento di formattazione esterno. Questa chiamata potrebbe essere sostituita con json.Marshal(u)
per stampare JSON senza spazi bianchi aggiuntivi. I due argomenti aggiuntivi per json.MarshalIndent
controllare il prefisso dell'output (che abbiamo omesso con la stringa vuota) ei caratteri da utilizzare per il rientro, che qui sono due caratteri spazio. Eventuali errori prodotti da json.MarshalIndent
vengono registrati e il programma termina utilizzandoos.Exit(1)
. Infine, abbiamo eseguito il cast di []byte
restituito da json.MarshalIndent
a string
e passato la stringa risultante fmt.Println
per la stampa sul terminale.
I campi della struttura appaiono esattamente come denominati. Questo non è il tipico stile JSON che potresti aspettarti, tuttavia, che utilizza l'involucro del cammello per i nomi dei campi. In questo prossimo esempio cambierai i nomi del campo per seguire lo stile della cassa del cammello. Come vedrai quando esegui questo esempio, questo non funzionerà perché i nomi dei campi desiderati sono in conflitto con le regole di Go sui nomi dei campi esportati.
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
)
type User struct {
name string
password string
preferredFish []string
createdAt time.Time
}
func main() {
u := &User{
name: "Sammy the Shark",
password: "fisharegreat",
createdAt: time.Now(),
}
out, err := json.MarshalIndent(u, "", " ")
if err != nil {
log.Println(err)
os.Exit(1)
}
fmt.Println(string(out))
}
Questo presenterà il seguente output:
Output
{}
In questa versione, abbiamo modificato i nomi dei campi per essere rivestiti di cammello. Ora Name
è name
, Password
è password
e finalmente CreatedAt
è createdAt
. All'interno del corpo di main
abbiamo cambiato l'istanza della nostra struttura per usare questi nuovi nomi. Passiamo quindi la struttura alla json.MarshalIndent
funzione come prima. L'output, questa volta è un oggetto JSON vuoto, {}
.
I campi Camel Casella richiedono correttamente che il primo carattere sia minuscolo. Sebbene a JSON non importi come denomini i tuoi campi, Go sì, poiché indica la visibilità del campo al di fuori del pacchetto. Poiché il encoding/json
pacchetto è un pacchetto separato dal main
pacchetto che stiamo utilizzando, dobbiamo maiuscolo il primo carattere per renderlo visibile a encoding/json
. Sembrerebbe che siamo a un punto morto. Abbiamo bisogno di un modo per trasmettere al codificatore JSON come vorremmo fosse chiamato questo campo.
È possibile modificare l'esempio precedente per esportare i campi correttamente codificati con nomi di campo con maiuscole di cammello annotando ogni campo con un tag struct. Il tag struct che encoding/json
riconosce ha una chiave json
e un valore che controlla l'output. Inserendo la versione con custodia in cammello dei nomi dei campi come valore della json
chiave, il codificatore utilizzerà invece quel nome. Questo esempio risolve i due tentativi precedenti:
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
)
type User struct {
Name string `json:"name"`
Password string `json:"password"`
PreferredFish []string `json:"preferredFish"`
CreatedAt time.Time `json:"createdAt"`
}
func main() {
u := &User{
Name: "Sammy the Shark",
Password: "fisharegreat",
CreatedAt: time.Now(),
}
out, err := json.MarshalIndent(u, "", " ")
if err != nil {
log.Println(err)
os.Exit(1)
}
fmt.Println(string(out))
}
Questo produrrà:
Output
{
"name": "Sammy the Shark",
"password": "fisharegreat",
"preferredFish": null,
"createdAt": "2019-09-23T18:16:17.57739-04:00"
}
Abbiamo cambiato i campi struct per renderli visibili ad altri pacchetti mettendo in maiuscolo le prime lettere dei loro nomi. Tuttavia, questa volta abbiamo aggiunto tag struct sotto forma di json:"name"
, dov'era "name"
il nome che volevamo json.MarshalIndent
usare durante la stampa del nostro struct come JSON.
Ora abbiamo formattato correttamente il nostro JSON. Si noti, tuttavia, che i campi per alcuni valori sono stati stampati anche se non sono stati impostati quei valori. Il codificatore JSON può eliminare anche questi campi, se lo desideri.
È comune sopprimere l'output dei campi non impostati in JSON. Poiché tutti i tipi in Go hanno un "valore zero", un valore predefinito su cui sono impostati, il encoding/json
pacchetto necessita di informazioni aggiuntive per poter dire che alcuni campi dovrebbero essere considerati non impostati quando assume questo valore zero. All'interno della parte del valore di qualsiasi json
tag struct, puoi suffissare il nome desiderato del tuo campo con ,omitempty
per indicare al codificatore JSON di sopprimere l'output di questo campo quando il campo è impostato sul valore zero. L'esempio seguente corregge gli esempi precedenti in modo che non restituiscano più campi vuoti:
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
)
type User struct {
Name string `json:"name"`
Password string `json:"password"`
PreferredFish []string `json:"preferredFish,omitempty"`
CreatedAt time.Time `json:"createdAt"`
}
func main() {
u := &User{
Name: "Sammy the Shark",
Password: "fisharegreat",
CreatedAt: time.Now(),
}
out, err := json.MarshalIndent(u, "", " ")
if err != nil {
log.Println(err)
os.Exit(1)
}
fmt.Println(string(out))
}
Questo esempio produrrà:
Output
{
"name": "Sammy the Shark",
"password": "fisharegreat",
"createdAt": "2019-09-23T18:21:53.863846-04:00"
}
Abbiamo modificato gli esempi precedenti in modo che il PreferredFish
campo abbia ora il tag struct json:"preferredFish,omitempty"
. La presenza ,omitempty
dell'aumento fa sì che l'encoder JSON salti quel campo, poiché abbiamo deciso di lasciarlo non impostato. Questo aveva il valore null
negli output dei nostri esempi precedenti.
Questo output ha un aspetto molto migliore, ma stiamo ancora stampando la password dell'utente. Il encoding/json
pacchetto fornisce un altro modo per ignorare completamente i campi privati.
Alcuni campi devono essere esportati da struct in modo che altri pacchetti possano interagire correttamente con il tipo. Tuttavia, la natura di questi campi può essere sensibile, quindi in queste circostanze vorremmo che il codificatore JSON ignori completamente il campo, anche quando è impostato. Questo viene fatto usando il valore speciale -
come argomento del valore per un json:
tag struct.
Questo esempio risolve il problema dell'esposizione della password dell'utente.
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
)
type User struct {
Name string `json:"name"`
Password string `json:"-"`
CreatedAt time.Time `json:"createdAt"`
}
func main() {
u := &User{
Name: "Sammy the Shark",
Password: "fisharegreat",
CreatedAt: time.Now(),
}
out, err := json.MarshalIndent(u, "", " ")
if err != nil {
log.Println(err)
os.Exit(1)
}
fmt.Println(string(out))
}
Quando esegui questo esempio, vedrai questo output:
Output
{
"name": "Sammy the Shark",
"createdAt": "2019-09-23T16:08:21.124481-04:00"
}
L'unica cosa che abbiamo cambiato in questo esempio rispetto ai precedenti è che il campo password ora usa il "-"
valore speciale per il suo json:
tag struct. Nell'output di questo esempio che il password
campo non è più presente.
Queste caratteristiche del encoding/json
pacchetto — ,omitempty
, "-"
, e altre opzioni — non sono standard. Ciò che un pacchetto decide di fare con i valori di un tag struct dipende dalla sua implementazione. Poiché il encoding/json
pacchetto fa parte della libreria standard, anche altri pacchetti hanno implementato queste funzionalità allo stesso modo per una questione di convenzione. Tuttavia, è importante leggere la documentazione per qualsiasi pacchetto di terze parti che utilizza tag struct per sapere cosa è supportato e cosa no.
I tag struct offrono un potente mezzo per aumentare la funzionalità del codice che funziona con i tuoi struct. Molte librerie standard e pacchetti di terze parti offrono modi per personalizzare il loro funzionamento attraverso l'uso di tag struct. Il loro utilizzo efficace nel codice fornisce questo comportamento di personalizzazione e documenta in modo succinto come questi campi vengono utilizzati per gli sviluppatori futuri.
Fonte dell'articolo originale su https://www.digitalocean.com
#go #golang
1658831286
In this tutorial, you'll learn how to use struct (structures) tags in Go (Golang). Go struct tags are annotations that appear after the type in a Go struct declaration.
Structures, or structs, are used to collect multiple pieces of information together in one unit. These collections of information are used to describe higher-level concepts, such as an Address
composed of a Street
, City
, State
, and PostalCode
. When you read this information from systems such as databases, or APIs, you can use struct tags to control how this information is assigned to the fields of a struct. Struct tags are small pieces of metadata attached to fields of a struct that provide instructions to other Go code that works with the struct.
Read more at https://www.digitalocean.com
#go #golang