Skip to content
Go

interface

Define and implement interfaces.

By EZ4Code Team
interfaceinterface

Code

package main

import "fmt"

type Animal interface {
    Sound() string
}

type Dog struct{ Name string }
func (d Dog) Sound() string { return d.Name + ": Woof" }

type Cat struct{ Name string }
func (c Cat) Sound() string { return c.Name + ": Meow" }

func makeSound(a Animal) {
    fmt.Println(a.Sound())
}

func main() {
    makeSound(Dog{"Buddy"})
    makeSound(Cat{"Kitty"})

    // Empty interface
    var any interface{} = 42
    fmt.Println(any)
}

Explanation

Go interfaces are implemented implicitly; implementing all methods satisfies the interface.

More Go Snippets