Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A type definition in Go creates a new, distinct type based on an existing underlying type. The newly defined type shares the same memory layout and representation as the underlying type, but the Go compiler treats them as entirely separate entities, enforcing strict type safety and requiring explicit conversions between them.
type NewTypeName UnderlyingType

Technical Characteristics

Type Identity and Strict Typing A defined type and its underlying type are not interchangeable. The compiler will reject implicit assignments or operations mixing the two types. To interact between a defined type and its underlying type, you must perform an explicit type conversion. Underlying Type Operations The defined type inherits the built-in operators of its underlying type. For example, if the underlying type is an int, the defined type supports arithmetic operators (+, -, *, /). If the underlying type is a string, it supports concatenation (+). Method Sets Methods bound to the underlying type are not inherited by the newly defined type. The defined type starts with an empty method set. However, you can declare new methods specifically bound to the defined type (provided the defined type is declared in the same package).

Syntax and Mechanics

package main

import "fmt"

// Type definition: 'ID' is a new type, 'int' is the underlying type.
type ID int

// Method bound to the newly defined type.
func (i ID) IsValid() bool {
    return i > 0
}

func main() {
    var myID ID = 100
    var rawInt int = 100

    // INVALID: mismatched types
    // myID = rawInt 
    // rawInt = myID 
    // var sum = myID + rawInt 

    // VALID: explicit type conversion
    myID = ID(rawInt)
    rawInt = int(myID)
    var sum = int(myID) + rawInt

    // VALID: calling a method on the defined type
    isValid := myID.IsValid()

    // Utilizing variables to satisfy the Go compiler's strict unused variable checks
    fmt.Println(myID, rawInt, sum, isValid)
}

Type Definitions vs. Type Aliases

It is critical to distinguish a type definition from a type alias, as they have fundamentally different compiler semantics:
  • Type Definition (type A B): Creates a completely new type. A and B are distinct. A does not inherit B’s methods.
  • Type Alias (type A = B): Introduces an alternate name for an existing type. A and B are identical in the eyes of the compiler. They share the exact same type identity, method sets, and require no conversion.
type DistinctString string // Type Definition: Distinct type
type AliasString = string  // Type Alias: Identical to string
Master Go with Deep Grasping Methodology!Learn More