← 中文资源

简体中文版本

类型别名对比命名类型的方法集

类型别名与原类型完全同体、方法集一并继承;命名类型字段相同但方法集为空,转换回原类型才能调用方法。注释掉的 Add 调用会直接编译失败。

阅读英文原文

实现说明

真正干活的是函数 Add、main,其余都是接线。

使用要点

  • 直接运行文件,输出会带上标签,比如 warehouse items:、depot converted then added:、depot untouched:——输出的每一行都能指回产生它的那次调用。
  • main 按顺序串起 Add;运行文件就会把这个流程跑一遍。

常见问题

运行「类型别名对比命名类型的方法集」会打印什么?

运行文件本身,warehouse items:、depot converted then added:、depot untouched: 这些前缀各对应一段演示逻辑。

签名一览:func (s *Store) Add(n int)

核心语句

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

代码示例

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)
}