Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composition of interfaces in Go

Tags:

oop

interface

go

Is there a way to make an interface also include the methods defined by another interface in Go?

For example:

type BasicDatabase interface {
    CreateTable(string) error
    DeleteTable(string) error
}

type SpecificDatabase interface {
    CreateUserRecord(User) error
}

I would like a way to specify that the SpecificDatabase interface contains the BasicDatabase interface. Similar to the way Go lets you do composition of structs.

This way my methods can take a type that implements SpecificDatabase, but still call CreateTable() on it.

like image 264
Michael Robinson Avatar asked May 11 '15 00:05

Michael Robinson


People also ask

What are interfaces in Go?

An interface type is defined as a set of method signatures. A value of interface type can hold any value that implements those methods.

How are interfaces implemented in Go?

To implement an interface in Go, you need to implement all the methods declared in the interface. Go Interfaces are implemented implicitly. Unlike Java, you don't need to explicitly specify using the implements keyword.

What is Golang composition?

Composition is a method employed to write re-usable segments of code. It is achieved when objects are made up of other smaller objects with particular behaviors, in other words, Larger objects with a wider functionality are embedded with smaller objects with specific behaviors.


1 Answers

This can be done the same way as when composing structs.

type BasicDatabase interface {
    CreateTable(string) error
    DeleteTable(string) error
}

type SpecificDatabase interface {
    BasicDatabase
    CreateUserRecord(User) error
}
like image 197
Evan Avatar answered Sep 22 '22 01:09

Evan