Sobes.tech
Junior — Middle

What is the difference between interfaces in Golang compared to similar features in other programming languages?

sobes.tech AI

Answer from AI

In Go, interfaces are implemented based on the principle of implicit implementation. This means that a type automatically implements an interface if it has all the methods required by the interface, without needing to explicitly declare this in the code (unlike Java or C#, where interface implementation must be explicitly declared).

This allows for more flexible and loosely coupled code, as types and interfaces do not depend on each other directly.

Example:

package main
import "fmt"

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

type MyReader struct{}

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

func main() {
    var r Reader = MyReader{} // implicit implementation of the interface
    fmt.Println(r)
}

Also, Go does not have class inheritance; interfaces are used for polymorphism and composition, which distinguishes them from many other languages.