Interfaces and Generics
Interfaces and type parameters for flexible APIs. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Search across all documentation pages
Interfaces and type parameters for flexible APIs. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Types satisfy interfaces by method set - no implements keyword.
type Stringer interface{ String() string }
type N int
func (n N) String() string { return fmt.Sprintf("%d", n) }
var s Stringer = N(3)
s.String() // "3"Extract concrete type from interface.
var i any = "hi"
s, ok := i.(string)
s // "hi"
// ok == trueBranch on dynamic type.
var i any = 7
s := ""
switch v := i.(type) {
case int:
s = fmt.Sprintf("int %d", v)
default:
s = "other"
}
s // "int 7"Type parameters in brackets.
func First[T any](xs []T) (T, bool) {
if len(xs) == 0 {
var z T
return z, false
}
return xs[0], true
}
v, ok := First([]int{9, 8})
v // 9
// ok == trueconstrain with interfaces / comparable.
func Max[T ~int | ~float64](a, b T) T {
if a > b { return a }
return b
}
Max(3, 5) // 5any is alias for interface{}.
var x any = 1
x // 1Interface is nil only if type and value are nil.
var p *int
var i any = p
i == nil // false (typed nil)comparable constraint for map keys.
func Has[K comparable, V any](m map[K]V, k K) bool {
_, ok := m[k]
return ok
}
Has(map[string]int{"a": 1}, "a") // trueParameterized structs.
type Pair[T any] struct{ A, B T }
Pair[int]{1, 2}.A // 1Methods may use type params of the receiver type.
type Box[T any] struct{ V T }
func (b Box[T]) Get() T { return b.V }
Box[string]{V: "x"}.Get() // "x"Compose interfaces.
type ReadWriter interface {
io.Reader
io.Writer
}
// types implementing both satisfy ReadWriterAccept interfaces, return structs (idiom).
// func Save(s Store) error
// prefer tiny interfaces at call sites~ includes underlying types.
type ID int
func F[T ~int](v T) T { return v }
F(ID(2)) // 2| in interface type sets.
type Number interface{ ~int | ~float64 }
func Dbl[T Number](v T) T { return v + v }
Dbl(2.5) // 5Check pointer before stuffing into interface.
var err error
err == nil // trueStack versions: Go 1.26.x · chi/gin/echo latest (verify at build)
Reviewed by Chris St. John·Last updated Jul 18, 2026