Created
April 11, 2018 14:22
-
-
Save potomak/1e87ebbdfe53ee9fd6593ec37fc6d44b to your computer and use it in GitHub Desktop.
Go interface example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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