Sobes.tech
Middle

What is the difference between the Go interface and interfaces in other programming languages?

sobes.tech AI

Answer from AI

The main difference of Go interfaces is that they are implemented implicitly (unexplicitly).

In other languages (e.g., Java, C#), a class must explicitly declare that it implements a specific interface (explicit implementation).

In Go, any type automatically satisfies an interface if it implements all the methods defined in that interface. Explicit declaration of implementation is not required.

Example (Go):

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

// Define the struct
type FileReader struct {
	// ... fields
}

// Implement the Read method for FileReader
func (fr FileReader) Read(p []byte) (n int, err error) {
	// ... reading logic
	return 0, nil // stub for example
}

// FileReader implicitly satisfies the Reader interface,
// as it has a matching Read method.

Example (Java - for comparison):

// Define the interface
interface Reader {
    int read(byte[] p);
}

// Define the class
class FileReader implements Reader { // Explicit implementation
    // ... fields

    @Override
    public int read(byte[] p) {
        // ... reading logic
        return 0; // stub for example
    }
}

Key advantages of implicit implementation in Go:

  • Decoupled design: Allows new libraries to define interfaces that can be satisfied by existing types without modification.
  • Flexibility: Simplifies creating generic functions that work with different types satisfying a single interface.
  • No need for "implements": Reduces boilerplate code.
  • Duck typing: If it looks like a duck and quacks like a duck, it is a duck. In this case, if a type implements the interface methods, it can be used as that interface.