gpt4 book ai didi

types - 为什么我可以键入别名函数并在不强制转换的情况下使用它们?

转载 作者:IT老高 更新时间:2023-10-28 12:57:33 25 4
gpt4 key购买 nike

在 Go 中,如果你定义了一个新类型,例如:

type MyInt int

然后您不能将 MyInt 传递给期望 int 的函数,反之亦然:

func test(i MyInt) {
//do something with i
}

func main() {
anInt := 0
test(anInt) //doesn't work, int is not of type MyInt
}

很好。但是为什么这同样不适用于函数呢?例如:

type MyFunc func(i int)
func (m MyFunc) Run(i int) {
m(i)
}

func run(f MyFunc, i int) {
f.Run(i)
}

func main() {
var newfunc func(int) //explicit declaration
newfunc = func(i int) {
fmt.Println(i)
}
run(newfunc, 10) //works just fine, even though types seem to differ
}

现在,我没有提示,因为它让我不必像第一个示例中那样显式地将 newfunc 转换为类型 MyFunc;它似乎不一致。我确信这是有充分理由的。谁能赐教?

我问的原因主要是因为我想以这种方式缩短我的一些相当长的函数类型,但我想确保这样做是预期和可接受的:)

最佳答案

原来,这是我对 Go 如何处理类型的误解,可以通过阅读规范的相关部分来解决:

http://golang.org/ref/spec#Type_identity

我不知道的相关区别是 namedunnamed 类型。

命名类型是具有名称的类型,例如 int、int64、float、string、bool。此外,您使用 'type' 创建的任何类型都是命名类型。

未命名 类型是诸如 []string、map[string]string、[4]int 之类的类型。它们没有名称,只是与它们的结构相对应的描述。

如果您比较两个命名类型,则名称必须匹配才能使它们可互换。如果您比较命名和未命名类型,那么只要底层表示匹配,就可以了!

例如给定以下类型:

type MyInt int
type MyMap map[int]int
type MySlice []int
type MyFunc func(int)

以下内容无效:

var i int = 2
var i2 MyInt = 4
i = i2 //both named (int and MyInt) and names don't match, so invalid

以下是可以的:

is := make([]int)
m := make(map[int]int)
f := func(i int){}

//OK: comparing named and unnamed type, and underlying representation
//is the same:
func doSlice(input MySlice){...}
doSlice(is)

func doMap(input MyMap){...}
doMap(m)

func doFunc(input MyFunc){...}
doFunc(f)

我有点内疚,我没有早点知道,所以我希望能为其他人澄清一下类型 lark !并且意味着比我最初想象的要少得多:)

关于types - 为什么我可以键入别名函数并在不强制转换的情况下使用它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19334542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com