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
Given the struct Restaurant
, create an instance of it with the following initial values:
name
: Codecademy SteakhousetypeOfRestaurant
: JapaneseyearEstablished
: 2011
Call this instance restaurant
.
Also, print out the restaurant
instance.
Print the value of each field of restaurant
on a separate line.
Change the values of name
to “Skillsoft Steakhouse” and yearEstablished
to “2022”.
Print out the updated restaurant
instance.