Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name instead of a type name as receiver.
Forgetting parentheses around the receiver.
✗ Incorrect
The method receiver must be a type name or pointer type. Here,
Person is correct to define the method on the struct value.2fill in blank
mediumComplete 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'
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.
✗ Incorrect
Using a pointer receiver
*Rectangle allows the method to work efficiently and modify the struct if needed.3fill in blank
hardFix 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'
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.
✗ Incorrect
To modify the struct field inside the method, the receiver must be a pointer
*Counter.4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a value receiver when pointer is preferred.
Using the wrong comparison operator.
✗ Incorrect
The method uses a pointer receiver
*Rectangle and compares width and height with ==.5fill in blank
hardFill 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'
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.
✗ Incorrect
The method uses a pointer receiver
*Person to modify the struct, takes a string parameter, and assigns it to p.Name.