logo

Programming Languages - Interfaces

Last Updated: 2024-01-21
  • Java interfaces are satisfied explicitly.
  • C++ abstract classes need to be extended explicitly
  • Go interfaces are satisfied implicitly. If a type defines all the methods of an interface, the type satisfies that interface.
  • Rust: trait

C++

C++ does not have a formal contruct for interfaces, it is achieved by defining a class with only pure virtual methods.

class Foo {
public:
  virtual int bar(int a) = 0;
};

class FooImpl : public Foo {
  // ...
}

Go

type Abser interface {
	Abs() float64
}

Go interfaces are implemented implicitly. (There's no implements keyword.)

interface{} == any type. (Go 1.18 introduces an any type as an alias to interface{}).

Assertion: i is an interface value, i.(T) asserts that the underlying type is T.

  • if true, t := i.(T) assigns the value to t.
  • if false:
    • if t := i.(T): panic.
    • if t, ok := i.(T): ok = false, no panic.

Interface embedding:

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

type Writer interface {
    Write(p []byte) (n int, err error)
}

// ReadWriter is the interface that combines the Reader and Writer interfaces.
type ReadWriter interface {
    Reader
    Writer
}

Rust

Rust uses trait to define methods that classes can implement.

trait Foo {
    fn bar(a: isize) -> isize;
}

struct FooImpl;

impl Foo for FooImpl {
    fn bar(a: isize) -> isize {
        return a;
    }
}

Java

Java uses interface keyword to define interfaces.

public interface Foo {
  public int bar(int a);
}

class FooImpl implements Foo {
  public int bar(int a) {
    return a;
  }
}

Starting from Java 8, you can implement default methods in interfaces; starting from Java 9, you can add private methods in interfaces.