NOTE

1.10 Type System

Built-in and custom Go types, type metadata, _type, extra metadata for built-in types, and uncommontype metadata for custom types.

GoCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What Types There Are

1.1. Built-in Types

int、float、string、slice、map、interface

1.2. Custom Types


type T1 int

type T2 struct {
    name string
}
type T3 interface {
    F1()
}

2. What Type Metadata Is

Both built-in types and custom types have type metadata. Together, this type metadata makes up Go’s type system. Both built-in types and custom types have an object header.

type _type struct {
    size       uintptr
    ptrdata    uintptr
    hash       uint32
    tflag      tflag
    align      uint8
    fieldalign uint8
    kind       uint8
    alg        *typeAlg
    gcdata     *byte
    str        nameOff
    ptrToThis  typeOff
}

2.1. Built-in Types

Built-in types contain additional information beyond the object header.

2.1.1. Examples

  • slice
type slicetype struct {
    typ   _type
    elem  *_type
}

  • Pointer
type ptrtype struct {
    typ   _type
    elem  *_type
}

2.2. Custom Types

  • They have an additional uncommontype.
type uncommontype struct {
    pkgpath nameOff// records the package path where the type is located;
    mcount  uint16 // records how many methods are associated with this type;
    _       uint16 // unused
    moff    uint32 // records how many bytes the array of method metadata is offset relative to this uncommontype structure
}

// Method metadata pointed to by moff
type method struct {
    name nameOff
    mtyp typeOff
    ifn  textOff
    tfn  textOff
}

2.2.1. Example

type myslice []string
func (ms myslice) Len(){
    fmt.Println(len(ms))
}
func (ms myslice) Cap(){
    fmt.Println(cap(ms))
}

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub