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 alias provides an alternative name for an existing type without creating a distinct, new type. To the Go compiler, the alias and the original type are completely identical and interchangeable.

Syntax

A type alias is declared using the type keyword followed by the alias name, an equals sign (=), and the existing type.
type AliasName = ExistingType
The inclusion of the = operator is the strict syntactic differentiator between a type alias and a standard type definition.

Primary Purpose

Introduced in Go 1.9, type aliases were designed specifically for large-scale refactoring and gradual code repair. They allow developers to move a type from one package to another without breaking backward compatibility for existing clients. Type aliases are generally not intended for domain modeling; standard type definitions are heavily preferred in those scenarios to enforce strict type safety.

Mechanics and Behavior

  • Type Identity: Because an alias does not create a new type, variables of the alias type and the original type can be assigned to each other directly without explicit type conversion.
  • Method Sets: An alias shares the exact same method set as the original type. If you define a method on the original type, it is available on the alias. Conversely, you cannot define new methods on an alias of a built-in type or a type defined in another package.
  • Reflection and Type Assertion: During runtime, the reflect package and type assertions will identify the alias strictly as its original type. The alias name is a compile-time construct and is not preserved in the type metadata of the compiled binary.

Type Alias vs. Type Definition

It is critical to distinguish an alias from a standard type definition. Go does not have “casting”; it relies on explicit type conversions for distinct types.
// Type Definition: Creates a distinct, new type.
// Requires explicit type conversion to assign to/from the underlying type.
type DefinedInt int

// Type Alias: Creates an alternate name for the exact same type.
// Requires NO type conversion to assign to/from the underlying type.
type AliasedInt = int

Code Example

The following example demonstrates the strict type equivalence between an alias and its original type:
package main

import (
	"fmt"
	"reflect"
)

type Original struct {
	Value int
}

// Declare a type alias
type Alias = Original

func main() {
	var orig Original = Original{Value: 42}
	
	// Implicit assignment is valid because Alias and Original are the same type
	var aliased Alias = orig 

	// Reflection proves the alias resolves to the original type
	fmt.Println(reflect.TypeOf(aliased)) // Output: main.Original
}
Master Go with Deep Grasping Methodology!Learn More