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,所以它可以调用。。。