0
0
Goprogramming~10 mins

Accessing struct fields in Go - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to access the field Name of the struct person.

Go
package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

func main() {
    p := Person{Name: "Alice", Age: 30}
    fmt.Println(p.[1])
}
Drag options to blanks, or click blank then click option'
AAge
BName
Cname
Dage
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase field names which do not exist.
Trying to access fields without the dot operator.
2fill in blank
medium

Complete the code to print the Age field of the struct user.

Go
package main

import "fmt"

type User struct {
    Username string
    Age      int
}

func main() {
    user := User{Username: "bob123", Age: 25}
    fmt.Println(user.[1])
}
Drag options to blanks, or click blank then click option'
AAge
BUsername
Cage
Dusername
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase field names that do not exist.
Trying to access fields without the dot operator.
3fill in blank
hard

Fix the error in accessing the Title field of the struct book.

Go
package main

import "fmt"

type Book struct {
    Title  string
    Author string
}

func main() {
    book := Book{Title: "Go Programming", Author: "John"}
    fmt.Println(book.[1])
}
Drag options to blanks, or click blank then click option'
Atitle
BAuthor
Cauthor
DTitle
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase field names that do not exist.
Confusing field names with variable names.
4fill in blank
hard

Fill both blanks to create a map of struct fields and filter by age greater than 20.

Go
package main

import "fmt"

func main() {
    type Employee struct {
        Name string
        Age  int
    }

    employees := []Employee{{"Anna", 22}, {"Ben", 19}, {"Cara", 25}}

    ages := map[string]int{}
    for _, e := range employees {
        if e.Age > 20 {
            ages[[1]] = [2]
        }
    }

    fmt.Println(ages)
}
Drag options to blanks, or click blank then click option'
Ae.Name
Be.Age
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping keys and values in the map.
Using incorrect field names.
5fill in blank
hard

Fill all three blanks to create a map of uppercase names to ages for employees older than 21.

Go
package main

import (
    "fmt"
    "strings"
)

func main() {
    type Employee struct {
        Name string
        Age  int
    }

    employees := []Employee{{"Dave", 23}, {"Eva", 20}, {"Frank", 24}}

    result := map[string]int{}
    for _, emp := range employees {
        if emp.[3] > 21 {
            result[[1]] = [2]
        }
    }

    fmt.Println(result)
}
Drag options to blanks, or click blank then click option'
Astrings.ToUpper(emp.Name)
Bemp.Age
CAge
DName
Attempts:
3 left
💡 Hint
Common Mistakes
Using field names without the struct variable prefix.
Not calling strings.ToUpper correctly.