Golang godoc - 解释组类型声明

Golang godoc - Explain group type declarations

我在 GIN 库和 Google 文档中看到了一段 GO 代码,如下所示

type (
    T0 []string
    T1 []string
    T2 struct{ a, b int }
    T3 struct{ a, c int }
    T4 func(int, float64) *T0
    T5 func(x int, y float64) *[]string
)

我不明白的是,这个分组在做什么以及这个实现的一些目的是什么(除非我错过了,否则文档中没有太多讨论这个主题)

杜松子酒图书馆的另一个例子

type (
    RoutesInfo []RouteInfo
    RouteInfo  struct {
        Method  string
        Path    string
        Handler string
    }
        Engine struct {
        RouterGroup
        HTMLRender  render.HTMLRender
        allNoRoute  HandlersChain
        allNoMethod HandlersChain
        noRoute     HandlersChain
        noMethod    HandlersChain
        pool        sync.Pool
        trees       methodTrees

        RedirectTrailingSlash bool


        RedirectFixedPath bool      
        HandleMethodNotAllowed bool
        ForwardedByClientIP    bool
    }
)

最后 - 抱歉,这是另一个主题,但与此相关

var _ IRouter = &Engine{}

为什么IRouter前面有一个_?我知道这是一个 blank identifier 但在那种情况下它有什么用途

代码

type (
   A int
   B string
)

功能与

相同
type A int
type B string

分组只是组织代码的一种方式。分组有时用于表示类型以某种方式相关。

中解释了空白标识符的使用。

我认为您的问题的第一部分已经得到解答。至于第二部分,代码

var _ IRouter = &Engine{}

创建 *Engine 实现 IRouter 接口的编译时检查。我们将 *Engine 类型的值赋给一个必须是 IRouter 类型的变量。如果 *Engine 不满足接口那么它不会编译。

这不是绝对必要的,但有些人喜欢把它放在他们定义类型的地方,以确保它始终满足预期的接口。

关于第一个问题

显示的语句是类型声明 来自 Go 语言规范: 类型声明将标识符(类型名称)绑定到与现有类型具有相同基础类型的新类型,并且为现有类型定义的操作也为新类型定义。新类型与现有类型不同。

TypeDecl = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) . TypeSpec = identifier Type .

通俗地说,你可以这样做:

type

例如

type Temperature uint8
type WeekTemp [7]Temperature

对于底层类型, 布尔、数字和字符串类型的命名实例是预先声明的。 复合类型是使用类型文字构造的

TypeLiteral = ArrayType | StructType | PointerType | FunctionType | InterfaceType | SliceType | MapType | ChannelType .

所以你也可以等效地做:

type (
    Temperature unit8
    WeekTemp [7]Temperature
)

复合类型的另一个例子

type Tree struct {
    leftChild, rightChild *Tree
}

对于第二个问题,

已编辑: 我没有意识到这一点,但在 go playground 上尝试,看起来 jcbwlkr 的答案确实是正确的。

所以尝试编译

type MyInterface interface{
    someMethod() 
}
type MyType struct{}
var _ MyInterface = &MyType{}

会报这个错

cannot use MyType literal (type *MyType) as type MyInterface in assignment: *MyType does not implement MyInterface (missing someMethod method)

因此它确实进行了编译时检查以确保 Engine 结构符合 IRouter 接口。整洁