dongshuql24533 2018-01-20 23:13
浏览 139
已采纳

在Go中将不同的类型重新分配给变量

Looking to do something like this

curr := foo()["blah"].(string)
curr, err := strconv.ParseFloat(curr, 64)

ERROR: cannot assign float64 to curr (type string) in multiple assignment

I dont want to make another temporary variable that I won't use after the conversion. I'm fairly new to Go so is there an approach that will help me avoid

temp := foo()["blah"].(string)
curr, err := strconv.ParseFloat(temp, 64)
  • 写回答

1条回答 默认 最新

  • dreamy6301 2018-01-20 23:39
    关注

    You are trying to force duck-typing here, and Go is statically-typed so that's going to be hairy or impossible. This justifies having another variable:

    if temp, ok := foo()["blah"].(string); ok {
            curr, err := strconv.ParseFloat(temp, 64)
            if err != nil {
                    panic(err)
            }
    }
    

    Go garbage collector is pretty sick. Having an extra variable temp for a few lines isn't that bad. Also don't forget guarding over type assertion.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决