Interfaces and Errors
Interface Slices
A slice of interface values can hold different concrete types with shared behavior.
Interface Slices
interface_slice.go
package main
import "fmt"
type Describer interface {
Describe() string
}
type Task struct {
Title string
}
func (t Task) Describe() string {
return "task:" + t.Title
}
type User struct {
Name string
}
func (u User) Describe() string {
return "user:" + u.Name
}
func main() {
var taskTitle =
items := []Describer{Task{Title: taskTitle}, User{Name: "Ada"}}
for _, item := range items {
fmt.Println(item.Describe())
}
}
package main
import "fmt"
type Describer interface {
Describe() string
}
type Task struct {
Title string
}
func (t Task) Describe() string {
return "task:" + t.Title
}
type User struct {
Name string
}
func (u User) Describe() string {
return "user:" + u.Name
}
func main() {
var taskTitle =
items := []Describer{Task{Title: taskTitle}, User{Name: "Ada"}}
for _, item := range items {
fmt.Println(item.Describe())
}
}
package main
import "fmt"
type Describer interface {
Describe() string
}
type Task struct {
Title string
}
func (t Task) Describe() string {
return "task:" + t.Title
}
type User struct {
Name string
}
func (u User) Describe() string {
return "user:" + u.Name
}
func main() {
var taskTitle =
items := []Describer{Task{Title: taskTitle}, User{Name: "Ada"}}
for _, item := range items {
fmt.Println(item.Describe())
}
}
interface slice
A slice typed as an interface can store any value that satisfies that interface.