Interfaces in Go

Introduction to Interfaces

Interfaces in Go define a set of method signatures but do not provide implementations. They enable polymorphism and dynamic behavior in Go programs.

Defining an Interface

An interface is defined using the type keyword followed by method signatures.

package main

import "fmt"

type Speaker interface {
    Speak()
}

type Dog struct {}

func (d Dog) Speak() {
    fmt.Println("Woof!")
}

func main() {
    var s Speaker
    s = Dog{}
    s.Speak()
}

Here, Dog implements the Speaker interface by defining the Speak method.

Implementing Multiple Interfaces

A struct can implement multiple interfaces in Go.

package main

import "fmt"

type Walker interface {
    Walk()
}

type Speaker interface {
    Speak()
}

type Person struct {
    Name string
}

func (p Person) Walk() {
    fmt.Println(p.Name, "is walking")
}

func (p Person) Speak() {
    fmt.Println("Hello, my name is", p.Name)
}

func main() {
    var w Walker = Person{Name: "Alice"}
    var s Speaker = Person{Name: "Alice"}
    w.Walk()
    s.Speak()
}

In this example, the Person struct implements both Walker and Speaker interfaces.

Empty Interfaces

An empty interface (interface{}) can hold values of any type.

package main

import "fmt"

func describe(i interface{}) {
    fmt.Printf("Value: %v, Type: %T\n", i, i)
}

func main() {
    describe("Hello")
    describe(42)
    describe(3.14)
}

This example demonstrates how an empty interface can store different types.

Type Assertion

Type assertion extracts the underlying value from an interface.

package main

import "fmt"

func main() {
    var i interface{} = "Hello"
    str, ok := i.(string)
    if ok {
        fmt.Println("String value:", str)
    } else {
        fmt.Println("Not a string")
    }
}

Here, we check if the interface holds a string value.

Conclusion

Interfaces in Go provide a way to achieve polymorphism. They allow defining behavior without specifying exact implementations.

In the next lesson, we will explore Concurrency in Go, which enables parallel execution of tasks.