0
0
Goprogramming~5 mins

Implementing interfaces in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an interface in Go?
An interface in Go is a type that defines a set of method signatures. Any type that implements these methods satisfies the interface automatically.
Click to reveal answer
beginner
How does a type implement an interface in Go?
A type implements an interface by having all the methods that the interface requires. There is no explicit declaration needed.
Click to reveal answer
beginner
Given this interface:<br>
type Speaker interface { Speak() string }
<br>How would a struct implement it?
The struct must have a method Speak() that returns a string. For example:<br>
func (p Person) Speak() string { return "Hello!" }
Click to reveal answer
intermediate
Can a pointer receiver implement an interface in Go?
Yes. If the interface method is implemented with a pointer receiver, only pointer types of that struct implement the interface. Value types do not.
Click to reveal answer
beginner
What happens if a type does not implement all methods of an interface?
The type does not satisfy the interface and cannot be assigned to a variable of that interface type.
Click to reveal answer
In Go, how do you declare that a type implements an interface?
ABy defining all methods of the interface on the type
BBy using the 'implements' keyword
CBy embedding the interface in the type
DBy importing the interface package
If an interface has method Foo(), which of these implements it?
AType with method Foo()
BType with method foo() (lowercase f)
CType with method Foo(int)
DType with no methods
What is true about pointer receivers and interfaces?
AInterfaces require value receiver methods
BValue types always implement interfaces with pointer receiver methods
CPointer receiver methods mean only pointer types implement the interface
DPointer receivers are not allowed in interfaces
Can a single type implement multiple interfaces?
ANo, a type can implement only one interface
BOnly if interfaces have no methods
COnly if interfaces are embedded
DYes, if it has all methods required by each interface
What happens if you assign a type that does not implement an interface to a variable of that interface type?
AIt works but methods are empty
BCompilation error
CRuntime panic
DIt silently ignores missing methods
Explain how a Go type implements an interface and why no explicit declaration is needed.
Think about how Go checks methods rather than declarations.
You got /3 concepts.
    Describe the difference between pointer receiver and value receiver methods in interface implementation.
    Consider which types can call the methods.
    You got /3 concepts.