Golang 中type name 和 type struct区别

golang中type 关键字大致有如下功能

1:定义结构,接口

type TestStruct struct{
    //XXXXXX

}
type TestInterface interface{
    //XXXXXXXXXX
}

2:以现有类型定义一个新的类型

type MyInt int

3:定义别名,仅仅是个别名 alias

type MyInt=int
type NameMap = map[string]interface{}

4:定义函数类型

type cbfunc func(s string) int

2和3有本质的区别

 type name和type struct 的区别

type Mutex struct {
	// nothing
}

func (m *Mutex) Lock() {
	fmt.Println("mutex lock")
}

func (m *Mutex) Unlock() {
	fmt.Println("mutex unlock")
}

type newMutex Mutex

type structMutex struct {
	Mutex
}

func main() {
	m1 := Mutex{}
	m1.Lock()

	// n1 := newMutex{}   
	// n1.Lock()      不具有Lock和Unlock方法

	x1 := structMutex{}
	x1.Lock()

}

n1不能执行Lock( )函数,因为golang中不支持隐式转换,虽然newMutex就是Mutex,但是语法上它是2中不同的类型,所以newMutex是不能调用Lock()和Unlock()方法的

x1可以自行,因为structMutex组合了Mutex,所以它可以调用。。。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值