Skip to content

Instantly share code, notes, and snippets.

@potomak
Created April 11, 2018 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save potomak/1e87ebbdfe53ee9fd6593ec37fc6d44b to your computer and use it in GitHub Desktop.
Save potomak/1e87ebbdfe53ee9fd6593ec37fc6d44b to your computer and use it in GitHub Desktop.
Go interface example
// Run at https://play.golang.org/p/gYCGtWOHGci
package main
import (
"fmt"
)
// Define an interface
type Foo interface {
Bar() int
}
// Define a struct
type Baz struct {
Value int
}
// Baz implements Foo interface
func (b *Baz) Bar() int {
return b.Value * 10
}
// Define another struct
type Bax struct {
Value int
}
// Define a generic function that accepts Foo interface implementers
func zzz(f Foo) int {
return f.Bar()
}
func main() {
// Test that `zzz` works on a Baz value
f := &Baz{12}
fmt.Printf("Baz --> %d", zzz(f))
// `zzz` doesn't work on a Bax value
// > g := &Bax{14}
// > fmt.Printf("Bax --> %d", zzz(g))
// Returns the error:
// > cannot use g (type *Bax) as type Foo in argument to zzz:
// > *Bax does not implement Foo (missing Bar method)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment