Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a method with a value receiver.
Go
type Counter struct {
count int
}
func (c Counter) Increment() {
c.count++
}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using * or & as the receiver variable name.
Using the type name instead of a variable name.
✗ Incorrect
The method receiver must be a variable name, here c is the value receiver variable.
2fill in blank
mediumComplete the code to call the Increment method on a value receiver.
Go
c := Counter{count: 0}
c.[1]()
fmt.Println(c.count)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase method names that do not exist.
Calling a method that is not defined.
✗ Incorrect
The method name is Increment with uppercase I to export it.
3fill in blank
hardFix the error in the method receiver declaration.
Go
func (c *Counter) Increment() {
c.count++
}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the type name as the receiver variable.
Using pointer dereference syntax in the receiver variable.
✗ Incorrect
The receiver variable must be a name like c, not a type or pointer dereference.
4fill in blank
hardFill both blanks to define a method with a value receiver and print the count.
Go
func (c Counter) PrintCount() {
fmt.Println(c.count)
}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using pointer type for value receiver.
Using wrong variable names.
✗ Incorrect
The receiver variable is c and the type is Counter for a value receiver.
5fill in blank
hardFill all three blanks to create a value receiver method that increments count and prints it.
Go
func (c Counter) IncrementAndPrint() {
c.count++
fmt.Println(c.count)
}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using pointer type for value receiver.
Using wrong field name.
Using wrong variable name.
✗ Incorrect
The receiver variable is c, the type is Counter, and the field accessed is count.