Interfaces let us write flexible code that works with different types. They help us organize and reuse code easily.
Interface use cases in Go
type InterfaceName interface {
MethodName(params) returnType
}An interface lists method signatures without implementations.
Any type that has those methods automatically implements the interface.
type Speaker interface {
Speak() string
}type Reader interface { Read(p []byte) (n int, err error) }
type Logger interface {
Log(message string)
}This program shows two types, Person and Robot, both implementing the Greeter interface by having a Greet method. The sayHello function accepts any Greeter and calls Greet. This lets us use different types interchangeably.
package main import "fmt" // Define an interface type Greeter interface { Greet() string } // Define a type that implements Greeter type Person struct { name string } func (p Person) Greet() string { return "Hello, " + p.name } // Define another type that implements Greeter type Robot struct { id int } func (r Robot) Greet() string { return fmt.Sprintf("Beep boop, I am robot #%d", r.id) } // Function that accepts any Greeter func sayHello(g Greeter) { fmt.Println(g.Greet()) } func main() { p := Person{name: "Alice"} r := Robot{id: 42} sayHello(p) // Person greets sayHello(r) // Robot greets }
Interfaces are satisfied implicitly in Go; you don't need to declare it explicitly.
Use interfaces to write flexible and testable code.
Empty interface interface{} can hold any type but should be used carefully.
Interfaces define behavior by listing method signatures.
Any type with those methods implements the interface automatically.
Interfaces let you write flexible, reusable, and testable code.
Practice
interface in Go?Solution
Step 1: Understand what an interface represents
An interface in Go lists method signatures without implementations.Step 2: Identify the role of interfaces
Any type that implements those methods satisfies the interface, enabling flexible code.Final Answer:
To define a set of method signatures that a type must implement -> Option AQuick Check:
Interface = method signatures [OK]
- Confusing interfaces with structs
- Thinking interfaces hold data
- Assuming interfaces perform calculations
Speaker with a method Speak() in Go?Solution
Step 1: Recall Go interface syntax
Interfaces are declared withtype Name interface { methods }.Step 2: Match the correct syntax
type Speaker interface { Speak() } correctly declaresSpeakeras an interface with methodSpeak().Final Answer:
type Speaker interface { Speak() } -> Option DQuick Check:
Interface declaration = type Speaker interface { Speak() } [OK]
- Using 'interface' keyword alone without 'type'
- Declaring interfaces as structs
- Adding 'func' keyword inside interface methods
package main
import "fmt"
type Speaker interface {
Speak()
}
type Dog struct {}
func (d Dog) Speak() {
fmt.Println("Woof!")
}
func saySomething(s Speaker) {
s.Speak()
}
func main() {
d := Dog{}
saySomething(d)
}Solution
Step 1: Check if Dog implements Speaker
Dog has methodSpeak(), so it satisfies Speaker interface.Step 2: Trace function call
Inmain,saySomething(d)callsd.Speak(), printing "Woof!".Final Answer:
Woof! -> Option AQuick Check:
Interface method call prints "Woof!" [OK]
- Assuming interface needs explicit implementation declaration
- Expecting compilation error due to interface
- Missing method receiver syntax
package main
import "fmt"
type Reader interface {
Read()
}
type File struct {}
func (f *File) Read() {
fmt.Println("Reading file")
}
func main() {
var r Reader
f := File{}
r = f
r.Read()
}Solution
Step 1: Check method receiver type
Read() is defined on pointer receiver*File, not onFilevalue.Step 2: Understand interface assignment rules
Assigningf(value) to interfacerfails becauseFiledoes not implementRead(), only*Filedoes.Final Answer:
Cannot assign value of type File to Reader interface -> Option CQuick Check:
Pointer receiver methods require pointer type assignment [OK]
- Ignoring pointer vs value receiver difference
- Expecting interface to accept any type
- Thinking methods must return values
type Walker interface {
Walk()
}
type Runner interface {
Run()
}
type Athlete interface {
Walker
Runner
}
type Person struct {}
func (p Person) Walk() {
fmt.Println("Walking")
}
func (p Person) Run() {
fmt.Println("Running")
}Which of the following statements is true?
Solution
Step 1: Understand interface embedding
Athlete embeds Walker and Runner, so it requires both Walk() and Run() methods.Step 2: Check Person methods
Person has both Walk() and Run() methods, so it satisfies Athlete interface automatically.Final Answer:
Person implements Athlete because it has both Walk and Run methods -> Option BQuick Check:
Interface embedding means combined methods [OK]
- Thinking explicit declaration is needed
- Believing interface embedding is invalid
- Assuming partial method implementation suffices
Ready to prove it?
Pass the test and this pattern moves unknown
