Struct Basics

Back

Loading concept...

๐Ÿ—๏ธ Building with Blueprints: Go Structs Basics

Imagine youโ€™re building with LEGOยฎ. Before you snap pieces together, you need a planโ€”a blueprint that says โ€œthis goes here, that goes there.โ€ In Go, that blueprint is called a Struct.


๐ŸŽฏ The Big Picture

A struct (short for โ€œstructureโ€) is like a recipe card or a form you fill out. It groups related information together under one name.

Real-life example:

  • Your ID card has: Name, Photo, Birthday, Address
  • A struct does the same thing for your code!
graph TD A["๐Ÿชช ID Card"] --> B["Name: Alex"] A --> C["Age: 10"] A --> D["School: Maple Elementary"]

๐Ÿ“ฆ 1. Struct Declaration โ€” Creating Your Blueprint

What is it?

A struct declaration is like drawing up a plan. Youโ€™re telling Go: โ€œI want to group these pieces of information together.โ€

The Recipe

type Person struct {
    Name string
    Age  int
}

Breaking it down:

  • type โ€” โ€œIโ€™m creating a new typeโ€
  • Person โ€” The name of your blueprint
  • struct โ€” โ€œItโ€™s a structureโ€
  • { } โ€” Everything inside is part of the plan

๐Ÿง’ Think of it like this:

Youโ€™re creating a form template. The form has blank spaces for โ€œNameโ€ and โ€œAgeโ€. You havenโ€™t filled it in yetโ€”you just designed the form!


๐Ÿท๏ธ 2. Struct Fields โ€” The Blank Spaces

What are fields?

Fields are the individual pieces of information inside your struct. Theyโ€™re like the blank lines on a form.

type Dog struct {
    Name   string  // Field 1
    Breed  string  // Field 2
    Age    int     // Field 3
    Fluffy bool    // Field 4
}

Each field has:

  1. A name โ€” What to call it (Name, Breed)
  2. A type โ€” What kind of info it holds (string, int, bool)

๐ŸŽจ Visual:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚     DOG FORM            โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Name:   ____________    โ”‚
โ”‚ Breed:  ____________    โ”‚
โ”‚ Age:    ____________    โ”‚
โ”‚ Fluffy: โ–ก Yes  โ–ก No     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

๐Ÿ–Š๏ธ 3. Struct Initialization โ€” Filling Out the Form

Now the fun part! You have your blueprintโ€”letโ€™s fill it in!

Method 1: Named Fields (Clear & Safe) โœ…

myDog := Dog{
    Name:   "Buddy",
    Breed:  "Golden",
    Age:    3,
    Fluffy: true,
}

Method 2: Ordered Values (Quick but risky) โš ๏ธ

myDog := Dog{"Buddy", "Golden", 3, true}

Order must match exactly!

Method 3: Start Empty, Fill Later

var myDog Dog
myDog.Name = "Buddy"
myDog.Age = 3

Method 4: Zero Values (Empty Form)

var emptyDog Dog
// Name = "" (empty string)
// Age = 0
// Fluffy = false

๐Ÿฐ Like ordering a cake:

  • Named fields: โ€œI want chocolate flavor, vanilla frosting, 2 layersโ€
  • Ordered values: โ€œChocolate, vanilla, 2โ€ (hope you remember the order!)

๐Ÿ“‹ 4. Struct Copy Behavior โ€” The Photocopier Rule

โšก The Surprise:

When you copy a struct, Go makes a complete photocopy. Changing the copy does NOT change the original!

original := Dog{Name: "Max", Age: 5}
copy := original      // Full photocopy!
copy.Name = "Rocky"   // Only copy changes

// original.Name is still "Max"!
// copy.Name is "Rocky"
graph LR A["๐Ÿ“„ Original<br/>Name: Max"] -->|Copy| B["๐Ÿ“„ Copy<br/>Name: Max"] B -->|Change| C["๐Ÿ“„ Copy<br/>Name: Rocky"] A -.->|Unchanged!| A

๐Ÿ–จ๏ธ Think of it like:

You photocopy a homework sheet. Your friend writes on their copy. Your original is still clean!

Why does this matter?

func birthday(d Dog) {
    d.Age = d.Age + 1  // This changes
}                       // the COPY only!

myDog := Dog{Name: "Luna", Age: 2}
birthday(myDog)
// myDog.Age is still 2! ๐Ÿ˜ฑ

The function got a photocopy, not the real thing!


๐ŸŽญ 5. Anonymous Structs โ€” Quick & Disposable

What are they?

Sometimes you need a quick struct for ONE thing. No need to name itโ€”just use it!

Example 1: One-time data

point := struct {
    X int
    Y int
}{10, 20}

Example 2: Quick configuration

config := struct {
    Debug   bool
    Version string
}{
    Debug:   true,
    Version: "1.0",
}

๐Ÿฅก Think of it like:

  • Named struct: A reusable plastic container with a label
  • Anonymous struct: A paper plateโ€”use once and done!

When to use:

โœ… Quick tests โœ… One-time data grouping โœ… Simple configurations โŒ Donโ€™t use if you need it more than once!


๐ŸŽ‰ Quick Recap

Concept What it does Everyday example
Declaration Creates the blueprint Drawing a form template
Fields The blank spaces Lines to fill in
Initialization Fills in the form Writing your info
Copy Behavior Makes photocopies Copying homework
Anonymous Quick throwaway struct Paper plate

๐Ÿš€ Your First Complete Example

package main

import "fmt"

// 1. Declaration
type Student struct {
    Name  string
    Grade int
    Pass  bool
}

func main() {
    // 3. Initialization
    alex := Student{
        Name:  "Alex",
        Grade: 95,
        Pass:  true,
    }

    // 4. Copy behavior
    backup := alex
    backup.Grade = 100

    fmt.Println(alex.Grade)   // 95
    fmt.Println(backup.Grade) // 100

    // 5. Anonymous struct
    temp := struct {
        X, Y int
    }{5, 10}

    fmt.Println(temp.X) // 5
}

๐Ÿ’ก Remember This!

Structs are like ID cards for your data. They keep related information together, neat and organized. And when you copy them, you get a whole new cardโ€”not just a reference to the same one!

Youโ€™ve got this! ๐ŸŽฏ

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.