Interface and Struct

Interface

💡
An interface type is defined as a set of method signatures.
package main

import "fmt"

// declare methods here
type I interface {
	M()
}

// declare variables here
type T struct {
	S string
}

// This method means type T implements the interface I,
// but we don't need to explicitly declare that it does so.
func (t T) M() {
	fmt.Println(t.S)
}

func main() {
	var i I = T{"hello"}
	i.M()
}

Union methods sets - embed interfaces

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

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

// ReadWriter's methods are Read, Write, and Close.
type ReadWriter interface {
	Reader  // includes methods of Reader in ReadWriter's method set
	Writer  // includes methods of Writer in ReadWriter's method set
}
From https://go.dev/ref/spec#Interface_types
  • But be careful of the same method names
type Reader interface {
	Read(p []byte) (n int, err error)
	Close() error
}

type ReadCloser interface {
	Reader   // includes methods of Reader in ReadCloser's method set
	Close()  // illegal: signatures of Reader.Close and Close are different
}

// error: duplicate methods Close
From https://go.dev/ref/spec#Interface_types

Struct

type person struct {
	name string
	age int
}

func main () {
	p := person{name: "Alvin"}
	p.age = 42
}

Embed struct

In this way, you can share common variables.
type Transportation struct {
	//
}

type Train struct {
	Transportation
}

type Bus struct {
	Transportation
}
 

Source