Go - Type

About

Rules

the rules are simple:

  • the assignment types must exactly match,
  • and nil may be assigned to any variable of interface or reference type.

Declaration and scope

type name underlying-type
  • Type declarations most often appear at package level, where the named type is visible throughout the package,
  • if the name is exported (it starts with an upper-case letter), it’s accessible from other packages as well.

List

Type switch

See https://golang.org/doc/effective_go.html#type_switch

var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
    fmt.Printf("unexpected type %T\n", t)     // %T prints whatever type t has
case bool:
    fmt.Printf("boolean %t\n", t)             // t has type bool
case int:
    fmt.Printf("integer %d\n", t)             // t has type int
case *bool:
    fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
    fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}

Assertion

v, ok = x.( T) 

// check type but discard result
_, ok = x.( T) 
  • ok is a booelan

Powered by ComboStrap