Sobes.tech
Senior

Mis on liidesed Go-s? Kuidas tüübid liideseid rakendavad?

sobes.tech AI

Vastus AI-lt

In Go, an interface is a set of methods that describe a behavior. A type implements an interface if it contains all the methods declared in the interface, without explicitly indicating the implementation of the interface.

This is called implicit interface implementation. Thanks to this, you can write more flexible and extensible code.

Example:

package main
import "fmt"

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

type File struct {}

func (f File) Read(p []byte) (n int, err error) {
    // read implementation
    return 0, nil
}

func main() {
    var r Reader
    f := File{}
    r = f // File implements Reader
    fmt.Println(r)
}

Here, the type File implements the Reader interface because it has a Read method with the required signature.