0
0
Goprogramming~10 mins

Implementing interfaces 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 declare that type Dog implements the Speaker interface.

Go
type Speaker interface {
    Speak() string
}

type Dog struct {}

func (d Dog) [1]() string {
    return "Woof!"
}
Drag options to blanks, or click blank then click option'
ASound
BTalk
CSay
DSpeak
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different method name like Talk or Say.
Not matching the method signature exactly.
2fill in blank
medium

Complete the code to create a variable of type Speaker and assign a Dog value to it.

Go
var s Speaker = [1]{}
Drag options to blanks, or click blank then click option'
ADog
BFish
CCat
DBird
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning a type that does not implement Speaker.
Using a pointer type when not required.
3fill in blank
hard

Fix the error in the method receiver to correctly implement the Speaker interface.

Go
func (d *Dog) [1]() string {
    return "Woof!"
}
Drag options to blanks, or click blank then click option'
ASpeak
BTalk
CSay
DSound
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different method name.
Not matching the interface method signature.
4fill in blank
hard

Fill both blanks to define a Cat type that implements Speaker with a pointer receiver.

Go
type Cat struct {}

func ([1] *Cat) [2]() string {
    return "Meow!"
}
Drag options to blanks, or click blank then click option'
Ac
BCat
CSpeak
DTalk
Attempts:
3 left
💡 Hint
Common Mistakes
Using the type name as receiver variable.
Wrong method name.
5fill in blank
hard

Fill all three blanks to create a function that accepts a Speaker and calls its Speak method.

Go
func saySomething([1] [2]) string {
    return [1].[3]()
}
Drag options to blanks, or click blank then click option'
As
BSpeaker
CSpeak
DDog
Attempts:
3 left
💡 Hint
Common Mistakes
Using a concrete type instead of the interface.
Calling a method not defined in the interface.