How to explicitly cast a type in Go?

huangapple go评论154阅读模式
英文:

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 // 无法将类型为ast.Decl的变量d用作*ast.FuncDecl类型的值进行赋值
    }

    // 更多类型的情况...
}

另外,尝试使用显式类型转换

fun = *ast.FunDecl(d)

会导致错误:

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

除了解决这个特定情况之外,这也引出了一个一般性问题,如何处理这样的类型转换情况?如果我知道变量的类型与我的转换匹配,我该如何将其转换为特定类型?

英文:

I have a statically declared variable

var fun *ast.FunDecl

and an array named decl of tyle ast.Decl that holds items of different types ast.GenDecl and *ast.FunDecl.

Now, during runtime I would like to iterate over the array and asign the first occurring item of type *ast.FunDecl to my variable fun.

Within my array-iteration, where d is the current array element, I am using:

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 ...
}

Also, trying to use the explicite cast

fun = *ast.FunDecl(d)

panics by saying:

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

Beyond solving this particular situation, this brings me to the general question, how to deal with such a type-casting situation like that? How can I cast a variable to a specific type if I know that its type matches my cast?

答案1

得分: 3

你需要将类型转换后的值 t 赋给变量,而不是 d。

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

你需要将 t 的值赋给 fun 变量。

英文:

you need to assign the type casted value t instead of d

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

huangapple
  • 本文由 发表于 2021年6月7日 19:37:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/67870943.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定