Sobes.tech
Principal

How are interfaces structured in Go?

sobes.tech AI

Answer from AI

In Go, interfaces are defined as a set of methods that a type must implement to be considered as conforming to that interface. The feature of Go is that implementing an interface does not require explicit declaration — if a type contains all the methods of the interface, it automatically implements it.

Example of an interface and its implementation:

package main
import "fmt"

type Reader interface {
    Read(p []byte) (n int, err error)
}

type MyReader struct {}

func (r MyReader) Read(p []byte) (int, error) {
    copy(p, "hello")
    return 5, nil
}

func main() {
    var r Reader = MyReader{}
    buf := make([]byte, 5)
    r.Read(buf)
    fmt.Println(string(buf)) // output: hello
}

Thus, interfaces in Go allow writing flexible and extensible code without tight coupling to specific types.