gpt4 book ai didi

go - 这个类型声明是什么意思?

转载 作者:IT王子 更新时间:2023-10-29 02:25:13 25 4
gpt4 key购买 nike

我实际上正在学习 golang(来自 .NET),但有一件事我不了解这种语言。有时我会发现这种声明:

https://github.com/golang/crypto/blob/master/ed25519/ed25519.go

// PublicKey is the type of Ed25519 public keys.
type PublicKey []byte

具体是什么意思?它是在创建一个继承自 []byte 的结构吗?

这只是一个别名吗?

我以为golang禁止继承

最佳答案

这是一个type declaration ,更具体地说是类型定义。它创建了一个新类型,将 []byte 作为其基础类型:

A type definition creates a new, distinct type with the same underlying type and operations as the given type, and binds an identifier to it.

创建新类型是因为它们可以简化多次使用它们,它们的标识符(它们的名称)可以在其他上下文中表达,而且——最重要的是——这样你就可以为它定义(附加)方法(你不能将方法附加到内置类型,也不附加到匿名类型或其他包中定义的类型。

这最后一部分(附加方法)很重要,因为即使不附加方法,您也可以轻松地创建和使用接受“原始”类型作为参数的函数,只有具有方法的类型才能实现列出的接口(interface)(“prescribe") 那些方法,并且如前所述,您不能将方法附加到某些类型,除非您创建从它们派生的新类型。

例如,[]int 类型永远不会实现 sort.Interface需要可排序(通过 sort 包),所以一个新类型 sort.IntSlice已创建(它是 type IntSlice []int),所需的方法附加到它,因此您可以将 sort.IntSlice 类型的值传递给 sort.Sort()函数,但不是 []int 类型的值。因为 sort.IntSlice[]int 作为它的基础类型,如果你有一个 []int 的值,你可以简单地 convert如果你想对它进行排序,它到 sort.IntSlice,就像这个例子(在 Go Playground 上试试):

is := []int{1,3,2}
sort.Sort(sort.IntSlice(is))
fmt.Println(is) // Prints: [1 2 3]

创建新类型时,不涉及“继承”。新类型将有 0 个方法。如果您想要“类似继承”的功能,您应该检查嵌入(与 struct types 相关),在这种情况下,嵌入器类型也将“具有”嵌入类型的方法。

关于go - 这个类型声明是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49402138/

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