Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse a function across multiple structs to satisfy an interface

Tags:

go

Is there anyway that you can use the same function across multiple structs to satisfy an interface?

For example:

package main

import "fmt"

type Animal interface {
  Speak() string
}

type Dog struct {}

func (d Dog) Speak() string {
  return "Woof!"
}

type Wolf struct {}

func (w Wolf) Speak() string {
  return "HOWWWWWWWWL"
}

type Beagle struct {}

func (b Beagle) Speak() string {
  return "HOWWWWWWWWL"
}

type Cat struct {}

func (c Cat) Speak() string {
  return "Meow"
}

func main() {
    var a Animal
    a = Wolf{}
    fmt.Println(a.Speak())
}

Because Wolf and Beagle share the exact same function, is there anyway to write that function once, then share it between the two structs so that they both satisfy Animal?

like image 902
sjmh Avatar asked Nov 17 '25 02:11

sjmh


1 Answers

You can create a parent struct that is embedded by each of the animals that "howl". The parent struct implements the Speak() string method, which means Wolf and Beagle implement the Animal interface.

package main

import "fmt"

type Animal interface {
  Speak() string
}

type Howlers struct {
}

func (h Howlers) Speak() string {
  return "HOWWWWWWWWL"
}

type Dog struct {}

func (d Dog) Speak() string {
  return "Woof!"
}

type Wolf struct {
    Howlers
}

type Beagle struct {
    Howlers
}

type Cat struct {}

func (c Cat) Speak() string {
  return "Meow"
}

func main() {
    var a Animal
    a = Wolf{}
    fmt.Println(a.Speak())
}

https://play.golang.org/p/IMFnWdeweD


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!