如何在 Go 中显式转换类型?

How to explicitly cast a type in Go?

我有一个静态声明的变量

var fun *ast.FunDecl

和一个名为 decl 的数组,类型为 ast.Decl,其中包含不同类型 ast.GenDecl*ast.FunDecl 的项目。

现在,在运行时我想遍历数组并将第一个出现的 *ast.FunDecl 类型的项目分配给我的变量 fun.

在我的数组迭代中,d 是当前数组元素,我使用的是:

switch t := d.(type)
{
    case *ast.FunDecl:
    {
        fun = d // cannot use d (variable of type ast.Decl) as *ast.FuncDecl value in assignment
    }

    // more type cases ...
}

此外,尝试使用显式转换

fun = *ast.FunDecl(d)

恐慌说:

cannot convert d (variable of type ast.Decl) to ast.FuncDecl.

除了解决这个特殊情况之外,这还让我想到了一个普遍的问题,如何处理这样的类型转换情况?如果我知道某个变量的类型与我的转换相匹配,我该如何将其转换为特定类型?

您需要分配类型转换值 t 而不是 d

switch t := d.(type){
    case *ast.FunDecl:
    {
        fun = t
    }
}