Golang Interfaces: Usage Guide & Examples

In Go language, interfaces are used to define a set of methods without including any implementation code. It serves as a specification for describing the behavior of objects.

Any object can implement an interface as long as it implements all the methods defined in the interface.

The usage of interfaces mainly includes several aspects:

  1. Defining an interface: Use the type keyword and interface{} to define an interface, for example:
  2. Writer is an interface that has a method named Write that takes a byte slice as a parameter and returns an integer and an error.
  3. Implementing interfaces: Any type that implements all the methods defined in an interface can be considered an implementation of that interface. For example:
  4. Create a struct called FileWriter and a method named Write, which takes a byte slice as input and returns an integer and an error as output.
  5. Using interfaces: Interface types can be used to declare variables, parameters, and return values. Interface variables can hold any object that implements the interface. For example:
  6. function WriteData(wrt Writer, data []byte) (int, error) {
    return wrt.Write(data)
    }

    func main() {
    fw := &FileWriter{}
    data := []byte(“Hello, World!”)
    WriteData(fw, data) // invoking interface method
    }

  7. Type assertion: It is possible to use type assertion to determine the actual type of object stored in an interface variable, and to retrieve the value of that type. For example:
  8. if fw, ok := wrt.(*FileWriter); ok {
    // fw can now be used to access methods and properties of the FileWriter type
    }

In summary, interfaces in Go language offer an abstract way to define the behavior of objects, enabling the feature of polymorphism. Through interfaces, code decoupling and flexible extension can be achieved.

bannerAds