kdocs
GitHub
Lang - Runtime
Lang - Runtime
  • Go
    • Modules & Packages
    • Variables
    • Structs
    • Interfaces
    • Functions
    • Control Structures
    • Erro Handling
    • Concurrency
    • Testing
    • Fuzzing
  • Web
    • V8 Engine
    • Node.js
      • New Project
    • Deno
      • New Project
Powered by GitBook
On this page
  • About
  • Creating
  • any interface
  • Using it
  • Embedded interfaces
  1. Go

Interfaces

About

Interfaces are useful as contracts, to state what fields or methods a struct should follow.

struct can be seen as the implementation description of the object.

interface can be seen as generic contracts, that structs can "implement".

Creating

Interfaces can have methods descriptions in them, as opposed to struct that can only have the fields descriptions.

// Since it is not Uppercase, it is only available inside the package
type saver interface {
    state bool
    Save(int, string) error
}

Interfaces with only one method

It is a convention that if an interface has only one method, the interface's name will be that method + er.

Ex.: Save() would make the interface name to be saver.

type saver interface {
    Save() error
}

any interface

Similar to Typescript any type, you have a generic interface that accepts anything with interface{} or any.

func print(value interface{}) {}

func print(value any){}

Using it

In Go you don't have to explicitly state that the structs Node and Todo have to implement saver.

The struct just have to implement whatever the interface states.

In the example, since the structs have a Save() method and state field, it is enough.

func saveData(data saver) {
    ...
}

node = node.New()
todo = todo.New()

saveData(note.Save())
saveData(todo.Save())

Embedded interfaces

In the same way as struct you may embbed interface,

type saver interface {
    Save() error
}

type outputtable interface {
    saver
    Display()
}
PreviousStructsNextFunctions

Last updated 1 month ago