在谈论struct和interface已经用到了type这个关键字。
另外,Go的type另外一种常用功能,是类似于C/C++的typedef。在Go的package中,这种用法非常常见。
A type declaration defines a new named type that has the same underlying type as an existing type. The named type provides a way to separate different and perhaps incompatible uses of the underlying type so that they can’t be mixed unintentionally.
type name underlying-type
示例:
package main
import (
"fmt"
)
type Hello interface {
out()
}
type MyInt int
func (myInt *MyInt) out() {
fmt.Println("MyInt.out():", *myInt)
}
func foo(i MyInt) {
fmt.Println("foo():", i)
}
func main() {
var i MyInt
i = 5
i.out() //MyInt.out(): 5
foo(i) // foo(): 5
foo(1) // foo(): 1
var x int
x = 100
//foo(x) //cannot use x (type int) as type MyInt in argument to foo
foo(MyInt(x)) // foo(): 100
}
注:foo(MyInt(x)) 给出了Go中强制类型转换的使用示例。——和C/C++的类型转换语法刚好相反(e.g. foo((MyInt)x))。
有疑问加站长微信联系(非本文作者)