So far, you’ve seen:
Variables for single values
Slices for lists
Maps for key-value stuff
But what if you want to group related data and give it structure? Like:
A
Userwith a name, age, and email.
That’s where structs come in.
A struct (short for “structure”) lets you create your own type — like a mini data model.
type User struct {
Name string
Age int
Email string
}Now User is a custom type, and you can make real users from it.
u := User{
Name: "Ashraf",
Age: 30,
Email: "ash@example.com",
}Print it:
fmt.Println(u)Output:
{Ashraf 30 ash@example.com}Use the . (dot) to get data:
fmt.Println(u.Name) // Ashraf
fmt.Println(u.Email) // ash@example.comYou can also update:
u.Age = 31Structs can be made of other structs:
type Address struct {
City string
Street string
}
type User struct {
Name string
Age int
Address Address
}Create one:
u := User{
Name: "Ash",
Age: 30,
Address: Address{
City: "KL",
Street: "Jalan ABC",
},
}Access nested data:
fmt.Println(u.Address.City) // KLQuick one-time structs without naming the type:
person := struct {
Name string
Age int
}{
Name: "Quick Guy",
Age: 20,
}Useful when you don’t need to reuse the type.
You can have a list of structs:
users := []User{
{Name: "Alice", Age: 25, Email: "a@example.com"},
{Name: "Bob", Age: 28, Email: "b@example.com"},
}
for _, u := range users {
fmt.Println(u.Name, "→", u.Email)
}Structs = your own data types
Use
type Name struct { ... }to createFields can be accessed with
.You can nest structs and use them in slices
No posts

Comments
Nothing yet. Say the first thing.
Sign in to join the conversation.