Interfaces

An interface in Go is a collection of method signatures without any concrete implementation. It defines what methods a type should have, but it doesn't provide the code for those methods.

package main

import "fmt"

// Define an interface named Writer with a method named Write.
type Writer interface {
    Write(data string)
}

// Implement the Writer interface for the ConsoleWriter type.
type ConsoleWriter struct{}

// Implement the Write method for ConsoleWriter.
func (cw ConsoleWriter) Write(data string) {
    fmt.Println(data)
}

func main() {
    // Create an instance of ConsoleWriter.
    var myWriter Writer = ConsoleWriter{}

    // Call the Write method through the Writer interface.
    myWriter.Write("Hello, Golang!")
}

In this example, we define an interface called Writer with a method Write. Then, we create a type ConsoleWriter that implements the Write method. Finally, in the main function, we create an instance of ConsoleWriter and use it through the Writer interface.