Learn

When we have complex groups of fields in our structs, they can be combined into their own struct! For example, in the Employee struct, we have two separate fields for the first and last name of the employee. We can combine those two strings into their own struct called Name:

type Name struct{ firstName string lastName string } type Employee struct{ name Name age int title string }

We create an instance of Employee like so:

carl := Employee{Name{“Carl”, “Carlson”}, 32, “Engineer”}

To access the fields of the nested struct (Name in this case), we chain together the field accesses like so:

fmt.Println(carl.name.lastName) // Output will be “Carlson”

We can also define the employee struct with the Name struct anonymously like so:

type Employee struct{ Name age int title string }

Notice how the Name file has no associated variable name with it.

Composing a struct in this way allows us to access the firstName and lastName fields directly from the Employee struct.

carl := Employee{Name{“Carl”, “Carlson”}, 32, “Engineer”} fmt.Println(carl.firstName) // Output will be “Carl” fmt.Println(carl.lastName) // Output will be “Carlson”

We, of course, cannot have two anonymous fields of the same type (i.e., two Name fields) as that would make it impossible to tell which field is being accessed (which firstName if two anonymous Name fields).

An anonymous field is used to field access easier and leads to cleaner code.

We now have the ability to organize struct information inside of existing structs! Let’s get some hands-on practice.

Instructions

1.

Create a struct called Circle that will contain the following two fields: point of type Point radius of type int

The point field represents the x and y coordinates of the center of the circle

2.

Print the x coordinate of the instance of Circle called circle.

3.

Inside the Circle struct, make the Point field anonymous.

Now that there is no point field by name you will need to modify the access you added in the last checkpoint.

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?