Struct e interfacce
Go Structs
Group related values into your own type with named fields.
Cosa imparerai
- Defining a struct
- Fields and %+v
- Structs are copied
User
Name"Ada"Age37ActivetrueYour own type with named fields
A struct is a type you define by naming its fields. It keeps related data together, such as the name, age and status of a user.
Fields are read and changed with a dot. %v prints the values and %+v adds the field names. Assigning a struct copies it, so changing guest does not change user. A struct can also be declared in place without a name.
Punti chiave
- Fields are read and changed with a dot.
- %+v prints the field names too.
- Assigning a struct copies it.
Esempio Go eseguibile
main.go
package main
import "fmt"
type User struct {
Name string
Age int
Active bool
}
func main() {
user := User{Name: "Ada", Age: 36, Active: true}
user.Age++
fmt.Println(user.Name, user.Age)
fmt.Printf("%v\n%+v\n", user, user)
guest := user // structs are copied on assignment
guest.Name = "Guest"
fmt.Println(user.Name, guest.Name)
point := struct{ X, Y int }{3, 4}
fmt.Println(point.X + point.Y)
}
Ada 37
{Ada 37 true}
{Name:Ada Age:37 Active:true}
Ada Guest
7Esercitati
Apri l'esempio nel compilatore online, cambia un valore o aggiungi una riga e prova a prevedere l'output prima di eseguirlo. Poi rompi il codice di proposito e leggi il messaggio del compilatore.
Hai finito questa lezione?
Segnala come imparata per tenere traccia dei tuoi progressi.
I tuoi progressi sono salvati in questo browser Accedi per conservarli su ogni dispositivo.
Esercitati con una sfida
Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.
Tutte le sfide