0
0
Goprogramming~10 mins

Why methods are used in Go - Test Your Understanding

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

Complete the code to define a method for the struct.

Go
func (p *Person) [1]() string {
    return p.name
}
Drag options to blanks, or click blank then click option'
APerson
Bname
Cfunc
DGetName
Attempts:
3 left
💡 Hint
Common Mistakes
Using the struct name instead of a method name.
Using 'func' as the method name.
2fill in blank
medium

Complete the code to call the method on the struct instance.

Go
p := Person{name: "Alice"}
fmt.Println(p.[1]())
Drag options to blanks, or click blank then click option'
Aname
BPerson
CGetName
Dfunc
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to access the field directly instead of calling the method.
Using the struct name as a method call.
3fill in blank
hard

Fix the error in the method receiver to allow modifying the struct.

Go
func (p [1] Person) SetName(newName string) {
    p.name = newName
}
Drag options to blanks, or click blank then click option'
A*
B&
Cvalue
Dref
Attempts:
3 left
💡 Hint
Common Mistakes
Using a value receiver which does not modify the original struct.
Using incorrect symbols like & or ref.
4fill in blank
hard

Fill both blanks to create a method that returns the full name.

Go
func (p [1] Person) FullName() string {
    return p.firstName + [2] + p.lastName
}
Drag options to blanks, or click blank then click option'
A*
B+
C-
D&
Attempts:
3 left
💡 Hint
Common Mistakes
Using a value receiver that may copy the struct.
Using minus or ampersand instead of plus for string concatenation.
5fill in blank
hard

Fill all three blanks to define and call a method that updates and returns the age.

Go
func (p [1] Person) SetAge(newAge int) {
    p.age = newAge
}

func (p Person) GetAge() int {
    return p.[2]
}

p := Person{}
p.[3](30)
fmt.Println(p.GetAge())
Drag options to blanks, or click blank then click option'
A*
Bage
CSetAge
DGetAge
Attempts:
3 left
💡 Hint
Common Mistakes
Using value receiver in SetAge which does not update the original struct.
Returning wrong field name.
Calling the wrong method to set age.