0
0
Goprogramming~10 mins

Defining methods 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 define a method named Greet for the Person struct.

Go
type Person struct {
    Name string
}

func (p [1]) Greet() string {
    return "Hello, " + p.Name
}
Drag options to blanks, or click blank then click option'
Aperson
B*Person
CPerson
Dp
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name instead of a type name as receiver.
Forgetting parentheses around the receiver.
2fill in blank
medium

Complete the code to define a method Area for the Rectangle struct that returns the area as an int.

Go
type Rectangle struct {
    Width, Height int
}

func (r [1]) Area() int {
    return r.Width * r.Height
}
Drag options to blanks, or click blank then click option'
Arectangle
B*Rectangle
Crect
DRectangle
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name instead of a type name.
Omitting the pointer when the method needs to modify the struct.
3fill in blank
hard

Fix the error in the method receiver declaration to correctly define method Double for Counter.

Go
type Counter struct {
    Value int
}

func (c [1]) Double() {
    c.Value = c.Value * 2
}
Drag options to blanks, or click blank then click option'
A*Counter
Bcounter
CCounter
Dc
Attempts:
3 left
💡 Hint
Common Mistakes
Using a value receiver which copies the struct and does not modify the original.
Using a variable name instead of a type name.
4fill in blank
hard

Fill both blanks to define a method IsSquare for Rectangle that returns true if width equals height.

Go
func (r [1]) IsSquare() bool {
    return r.Width [2] r.Height
}
Drag options to blanks, or click blank then click option'
A*Rectangle
BRectangle
C==
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using a value receiver when pointer is preferred.
Using the wrong comparison operator.
5fill in blank
hard

Fill all three blanks to define a method UpdateName for Person that sets the Name field to a new value.

Go
func (p [1]) UpdateName(newName [2]) {
    p.Name = [3]
}
Drag options to blanks, or click blank then click option'
A*Person
Bstring
CnewName
DPerson
Attempts:
3 left
💡 Hint
Common Mistakes
Using a value receiver which does not modify the original struct.
Forgetting to use the parameter name when assigning.