Interfaces

Contents

Interfaces#

An interface is a set of method signatures. A type satisfies an interface implicitly (no implements keyword); structural satisfaction is the operator’s main abstraction tool.

Declare an interface.

type Stringer interface {
    String() string
}

A struct satisfies it by having the right method set.

type User struct{ Name string }

func (u User) String() string { return "user:" + u.Name }

Assign through the interface.

var s Stringer = User{Name: "rk"}

The empty interface any (alias for interface{}) holds any value; the operator narrows with a type assertion or type switch.

Type assertion with comma-ok.

var x any = 42
n, ok := x.(int)

Type switch.

switch v := x.(type) {
case int:    fmt.Println("int", v)
case string: fmt.Println("string", v)
default:     fmt.Println("other")
}

References#

  • OOP for method sets and embedding.

  • Structs for the typical interface-implementing type.