Golang Program to Create an Interface Named Animal That Defines a Speak Method


The speak method in golang is obtained by the customized functions that you can define to achieve a specific functionality. Speak is a user-defined function that performs the task for which it is created. In this article, we are going to create an animal interface that defines the speak method. This interface serves as a blueprint for any type that wants to be considered an animal and provides a contract for implementing the Speak behavior. Here we are going to use three different methods: direct interface implementation, struct embedding as well as interface assertion along with examples to elaborate the concept. In this article, we create an interface called Animal that defines a method named Speak.

Syntax

type Animal interface {Speak() string}

The Syntax type Animal interface { Speak() string } defines an interface named Animal in Go, specifying that any type implementing this interface must have a method named Speak that takes no arguments and returns a string.

OuterStruct struct

In this Syntax, OuterStruct embeds EmbeddedStruct by including it as a field within OuterStruct.

EmbeddedStruct

The embedded struct's fields and methods are automatically accessible within OuterStruct. Methods specific to OuterStruct can be defined, and methods of EmbeddedStruct can be accessed using o.EmbeddedStruct.Method().

value, ok := variable.(InterfaceType)

The Syntax value, ok := variable.(InterfaceType) is used in Go for interface assertion. It attempts to assert that the value stored in variable implements the InterfaceType, and if successful, assigns the asserted value to value and sets ok to true; otherwise, ok is set to false.

Algorithm

  • Step 1 − Define an interface named Animal with the Speak method signature.

  • Step 2 − Implement the Speak method for specific animal types by creating concrete types that satisfy the Animal interface.

  • Step 3 − Within the Speak method implementation for each animal type, define the specific behavior or sound that the animal makes.

  • Step 4 − Create instances of different animal types and assign them to variables of type Animal.

  • Step 5 − Invoke the Speak method on each animal variable to trigger the specific sound or behavior defined for that animal.

Example 1

In this example code below, we first declare an interface named Animal with a Speak method that returns a string. Then, we define two struct types − Dog and Cat, which implement the Animal interface by providing an implementation for the Speak method. Then we call the Speak method on each Animal interface variable, and the respective implementation for Dog and Cat is invoked, producing the expected output of "Woof!" and "Meow!".

package main

import "fmt"

type Animal interface {
   Speak() string
}

type Dog struct{}

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

type Cat struct{}

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

func main() {
   dog := Dog{}
   cat := Cat{}

   var animal1 Animal = dog
   var animal2 Animal = cat

   fmt.Println(animal1.Speak()) 
   fmt.Println(animal2.Speak()) 
}

Output

Woof!
Meow!

Example 2

The below code demonstrates struct embedding and interface implementation in Go. It defines an interface named Animal with a Speak() method. The OuterStruct struct embeds EmbeddedStruct, inheriting its fields and methods. By calling the Speak() method on an instance of OuterStruct, the code prints "This is the embedded struct speaking!" as the output.

package main

import "fmt"

type Animal interface {
   Speak() string
}

type EmbeddedStruct struct{}

func (e EmbeddedStruct) Speak() string {
   return "This is the embedded struct speaking!"
}

type OuterStruct struct {
   EmbeddedStruct
}

func main() {
   outer := OuterStruct{}

   fmt.Println(outer.Speak()) // Output: This is the embedded struct speaking!
}

Output

This is the embedded struct speaking!

Example 3

The below code demonstrates the usage of interfaces and type assertion in Go. It defines an interface named Animal with a Speak() method. Two types, Dog and Cat, are implemented with their respective Speak() methods. In the main() function, instances of Dog and Cat are created and asserted to the Animal interface. The code then checks if the assertions are successful and call the Speak() method on the asserted values, resulting in the outputs "Woof!" and "Meow!" respectively. 

package main

import "fmt"

type Animal interface {
   Speak() string
}

type Dog struct{}

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

type Cat struct{}

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

func main() {
   dog := Dog{}
   cat := Cat{}

   var animal1 Animal = dog
   var animal2 Animal = cat

   if value, ok := animal1.(Dog); ok {
      fmt.Println(value.Speak())
   }

   if value, ok := animal2.(Cat); ok {
      fmt.Println(value.Speak())
   }
}

Output

Woof!
Meow!

Conclusion

In this article, we have looked at how to make an interface named "Creature" with a "Talk" strategy in Go. By characterizing an interface and executing it with distinctive struct sorts, we empower polymorphic behavior, permitting objects of distinctive sorts to be traded. The Creature interface gives a contract that guarantees any sort execution it'll have a "Talk" strategy. This adaptability permits us to type in more secluded and extensible code.

Updated on: 20-Jul-2023

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements