go - 如何在 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。
除了解决这个特殊情况之外,这给我带来了一个普遍的问题,如何处理这样的类型转换情况?如果我知道它的类型与我的类型匹配,我如何将变量转换为特定类型?
解决方案
您需要分配类型转换值 t 而不是 d
switch t := d.(type){
case *ast.FunDecl:
{
fun = t
}
}
推荐阅读
- python - Python3 看不到 opencv-python、numpy、PyQt5
- python - 如何在 Python 中恢复切片边界?
- python - Kivy:从 RecycleView 更新 ScreenManager 屏幕上的字段
- soap - 在 Azure 函数中使用 SOAP 服务
- google-chrome - 打开 Chrome 开发工具时如何默认关闭检查器?
- go - Golang同时从一个tcp连接读取
- c++ - 如何使用 restbed 设置新的 C++ 项目?
- delphi - 使用 Delphi 检索 Word 服务器属性
- javascript - 不和谐消息发送之间的时间不起作用
- c++ - Qt中的RGB图像处理