ProgrammingGo developer / API engineer

How to implement and use type alias in Go, how do they differ from new types, and when is this particularly important?

Pass interviews with Hintsage AI assistant

Answer.

Background:

The introduction of type aliases in Go is related to the need to ensure a smoother transition between API versions when a type moves from one package to another. Prior to Go 1.9, only new type declarations were used, but now type aliases are supported.

Problem:

Many confuse alias and new type — mistakenly consider them identical, which leads to errors during conversions, methods, and interface passing.

Solution:

Type alias creates an alternative name for an existing type, while declaring a new type is creating a new unique type based on an existing one. Aliases allow for maintaining backward compatibility and integrating old and new types without conversion.

Code example:

// New type type MyString string // Type alias type MyStringAlias = string

Key features:

  • Alias and the original type are fully interchangeable
  • New type is standalone, can add methods and implicit conversion is not possible
  • Alias is convenient for migrations and re-exporting types between packages

Tricky Questions.

Can you add methods to a type through alias?

No, methods can only be added to new types, and the alias is not a new type, but the same as the original Type.

type Alias = int // func (a Alias) Method() {} // error!

What is the difference in comparing alias types and new types?

Alias is comparable to the base type and takes its value without conversion. New type is incompatible even if based on the same type.

type T1 = int var a T1 = 10 // ok var b int = a // ok type T2 int var c T2 = 10 // var d int = c // compilation error

When is alias better than new type?

When re-exporting a type between packages or ensuring transparent API migration without recompiling client code. For example:

type OldType = NewType // alias is more convenient for maintaining old API versions

Common Mistakes and Anti-Patterns

  • Confusion between alias and new type in naming
  • Reusing alias while trying to extend functionality
  • Using alias where an encapsulated type with methods is needed

Real-Life Example

Negative Case

In the project, a type is renamed using a new type instead of an alias, which breaks compatibility

type OldType int

Pros:

  • Ability to define custom methods

Cons:

  • Requires manual type conversion when migrating, breaking backward compatibility

Positive Case

Type alias is used for transparent API migration

type OldType = NewType

Pros:

  • No compatibility issues, no need to change existing code

Cons:

  • Cannot add new methods only through alias