Start learning free

LESSON 282 OF 671 · FUNCTIONS & CLASSES

Member Variables in Go

Lesson

TL ; DR:

  • A field is a variable that lives inside a struct. Each value of that struct type has its own copy.


  • Declare fields inside a type ... struct block so other code can read and write them:

    type Dog struct {
        name string
        age  int
    }
    

  • Access them on a value with the dot operator: dog.name = "Rex"



Full lesson:

Right now your Dog struct is just an empty shell — every Dog value you create is identical. We need a way to attach data to each value.

That's what fields are for. A field is a variable that belongs to a struct — and each value created from that struct type gets its own copy of every field.


Declaring fields

type Dog struct {
    name string
    age  int
}
  • Fields with an uppercase first letter are exported — accessible from outside the package. Lowercase fields are accessible within the same package.

  • name string is a regular field declaration.


Reading and writing

dog := Dog{}
dog.name = "Rex"        // write
dog.age = 4
fmt.Println(dog.name)  // read

Each value has its own slot for every field, so two dogs can have different names without interfering.


Your task

Update the Dog struct to have two fields: name (a string) and age (an int). Then in mainFunction, set them on the dog value so the pre-filled fmt.Printf prints:

Rex is 4 years old
STEP 1 OF 3
    Ctrl + Enter to check