Numeric type aliases

February 22, 2023

Numeric Types

byte        alias for uint8
rune        alias for int32

To avoid portability issues all numeric types are defined types and thus distinct except byte, which is an alias for uint8, and rune, which is an alias for int32.

As with other aliases in Go, this means that the same type simply has two (or perhaps more) identifiers, which are completely interchangeable.

This means that byte is not a distinct type, simply backed by a uint8 type. It is the same type, with just a different identifier. This means that, for example, anywhere in Go code you see byte you could instead type uint8, or vice versa.

This is distinct from the case mentioned yesterday between int vs int32/int64, which may have the same underlying data structure, but are still distinct types.

So how can you tell which size your int is while running your program? Well, first, if you’re trying to determine this at runtime, first consider whether that’s really necessary. 😊 Can you design your program not to require that? But if you really must know, the unsafe.Sizeof function has your back. It will report the number of bytes used by a the argument’s zero value.

	fmt.Println(unsafe.Sizeof(int(0))) // 8 on a 64-bit system, 4 on a 32-bit system

Quotes from The Go Programming Language Specification, Version of January 19, 2023

Share this

Related Content

Empty structs

We finally we have enough knowledge for the EBNF format not to seem completely foreign, so let’s jump back and take a look at that, with the examples provided in the spec… Struct types … StructType = "struct" "{" { FieldDecl ";" } "}" . FieldDecl = (IdentifierList Type | EmbeddedField) [ Tag ] . EmbeddedField = [ "*" ] TypeName [ TypeArgs ] . Tag = string_lit . // An empty struct.

Struct tags

Struct types … A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. An empty tag string is equivalent to an absent tag. The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored. struct { x, y float64 "" // an empty tag string is like an absent tag name string "any string is permitted as a tag" _ [4]byte "ceci n'est pas un champ de structure" } // A struct corresponding to a TimeStamp protocol buffer.

Struct method promotion

Yesterday we saw an example of struct field promotion. But methods (which we haven’t really discussed yet) can also be promoted. Struct types … Given a struct type S and a named type T, promoted methods are included in the method set of the struct as follows: If S contains an embedded field T, the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T.