Junior — Middle
Can you give an example of a situation where using interfaces helps structure the code?
sobes.tech AI
Answer from AI
Interfaces in Go help structure code by defining a set of methods that different types must implement, which facilitates extensibility and testing.
Example: suppose you have different types of data storage — database, cache, file system. You can define an interface Storage with a method Save(data string) error.
package main
import "fmt"
// Interface
type Storage interface {
Save(data string) error
}
// Implementation for database
type DBStorage struct{}
func (db DBStorage) Save(data string) error {
fmt.Println("Saving to database:", data)
return nil
}
// Implementation for file system
type FileStorage struct{}
func (fs FileStorage) Save(data string) error {
fmt.Println("Saving to file:", data)
return nil
}
func process(s Storage, data string) {
s.Save(data)
}
func main() {
db := DBStorage{}
file := FileStorage{}
process(db, "data for DB")
process(file, "data for file")
}
This approach allows writing code that works with the abstraction Storage, independent of specific implementations, which simplifies maintenance and testing.