Go · Stage 7 – Structuring Data · Lesson 42 of 64

Creating and Using Structs

Create one struct value and read its fields.

Go code

type Person struct { Name string }
person := Person{Name: "Maya"}
fmt.Println(person.Name)
Line-by-line explanation
  1. A Person type is declared.
  2. The literal creates one Person.
  3. Name receives Maya.
  4. Dot notation reads the field.
Expected output
Maya

This is the expected result.

Tiny Practice

Starter scenario

Create a Book with Title Go Basics.

Go code

type Book struct { Title string }
book := Book{CHANGE_ME}
fmt.Println(book.Title)
Line-by-line explanation
  1. The type and output are ready.
  2. The literal content is missing.
Expected output
(complete the starter first)

The starter intentionally contains CHANGE_ME.

Hint
  1. Use Title:.
  2. Add the quoted text.
  3. Keep braces.
Show Solution

Go code

type Book struct { Title string }
book := Book{Title: "Go Basics"}
fmt.Println(book.Title)
Line-by-line explanation
  1. The literal assigns Title.
  2. Dot notation reads it.
Expected output
Go Basics

This is the expected result.