Learn

We’ve defined our struct and created an instance, it’s time to use them. In this exercise, we will explore how to access and modify a struct’s variables.

Let’s say we have an instance of the Student struct:

john := Student{"John", "Smith", 14, 9}

We can access individual fields within struct using the name of the variable, a ., and the name of the field. We could access John’s first name like so:

fmt.Println(john.firstName)

We can change the value of a field with an assignment statement:

john.age = 15

John’s just turned 15!

Using field access and modification finally allows us to be able to use structs in calculations for our program.

Now let’s practice this concept!

Instructions

1.

Given the struct Restaurant, create an instance of it with the following initial values:

  • name: Codecademy Steakhouse
  • typeOfRestaurant: Japanese
  • yearEstablished: 2011

Call this instance restaurant.

Also, print out the restaurant instance.

2.

Print the value of each field of restaurant on a separate line.

3.

Change the values of name to “Skillsoft Steakhouse” and yearEstablished to “2022”.

4.

Print out the updated restaurant instance.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?