go go/book/learninggo

interfaces are a powerful and flexible way to define behavior.
An interface specifies a set of method signatures (behavior) without specifying the underlying data type that implements them.
The main concept behind interfaces in Go is implicit implementation, meaning a type doesn’t need to explicitly declare that it implements an interface.

type Speaker interface {
    Speak() string
}
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!"
}
 
type Llama struct {
}
 
func (l Llama) Speak() string {
	return "?????"
}
 
func main() {
	animals := []Animal{Dog{}, Cat{}, Llama{}} // Slice
	for _, animal := range animals {
		fmt.Println(animal.Speak())
	}
}
 

Go - Methods


Empty Interface

The empty interface interface{} is a special case and can hold any type because all types implement at least zero methods.This is commonly used when you want a function to accept any type of argument.

func printAnything(x interface{}) {
    fmt.Println(x)
}
 
func main() {
    printAnything(42)        // Passes an int
    printAnything("Hello")   // Passes a string
    printAnything(true)      // Passes a bool
}

How to Use Interfaces


Type Assertion

package main
import "fmt"
 
func main() {
 
  // create an empty interface
  var a interface{}
  a = 12
 
  // type assertion
  interfaceValue, booleanValue := a.(int)
 
  fmt.Println("Interface Value:", interfaceValue)
  fmt.Println("Boolean Value:", booleanValue)
}
 
// Output
// Interface Value: 12
// Boolean Value: true
 

here, (int) checks if the value of a is an integer or not. If true, the value will be assigned to interfaceValue.

Otherwise, the program panics and terminates

Go - Defer,Panic & Recover > Panic