首页 > 解决方案 > 如何在 Go 中显式转换类型?

问题描述

我有一个静态声明的变量

var fun *ast.FunDecl

decl以及一个名为tyle的数组,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)

惊慌失措地说:

无法将 d(ast.Decl 类型的变量)转换为 ast.FuncDecl。

除了解决这个特殊情况之外,这给我带来了一个普遍的问题,如何处理这样的类型转换情况?如果我知道它的类型与我的类型匹配,我如何将变量转换为特定类型?

标签: gotypescasting

解决方案


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

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

推荐阅读