RSS Amplifier

Ashraf Latif · Aug 5, 2025

Mastering Go 10: Structs in Go – Making Your Own Custom Data Types 🏗️

0
Sign in to vote or save

Ashraf Latif · Ashraf Latif

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 User with 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.com

You can also update:

u.Age = 31

Structs 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) // KL

Quick 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 create

  • Fields can be accessed with .

  • You can nest structs and use them in slices

No posts

Read the original on ceghap.substack.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.