Type Alias Versus Named Type Methods

A type alias is the same type including its method set, while a named type over the same struct starts with an empty method set.

GoData Integrity

Code

gosnippet
27 lines
package main

import "fmt"

type Store struct{ items int }

func (s *Store) Add(n int) { s.items += n }

// type alias: identical to Store, methods included
type Warehouse = Store

// named type: distinct type over the same struct, no inherited methods
type Depot Store

func main() {
	var w Warehouse
	w.Add(3) // alias keeps Store's method set
	fmt.Println("warehouse items:", w.items)

	var d Depot
	d.items = 2 // fields carry over, methods do not
	// d.Add(1) // compile error: Depot has no Add method
	s := Store(d)
	s.Add(1)
	fmt.Println("depot converted then added:", s.items)
	fmt.Println("depot untouched:", d.items)
}

Inside the snippet

Type Alias Versus Named Type Methods keeps everything in the functions Add and main.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

Entry signature: func (s *Store) Add(n int)

The file’s steps are announced right in the output: warehouse items:, depot converted then added:, depot untouched:.

The demo flow inside main is Add — run the file to see it end to end.

The core lines, annotated

func (s *Store) Add(n int) { s.items += n }

Interactive Tools for This Topic

FAQ

What does Type Alias Versus Named Type Methods print when run?
No setup needed: run the file and look for labeled lines like `warehouse items:`, `depot converted then added:`, `depot untouched:` in the output.