duanbeng1923 2018-11-06 10:38
浏览 23

如何在Golang中为单值上下文错误修复多值?

package main
import "fmt"

func main() {
    fmt.Println("Enter a number: ")
    var addendOne int = fmt.Scan()
    fmt.Println("Enter another number: ")
    var addendTwo int = fmt.Scan()
    sum := addendOne + addendTwo
    fmt.Println(addendOne, " + ", addendTwo, " = ", sum)
}

This raises an error:

multiple values in single-value context.

Why does it happen and how do we fix it?

  • 写回答

3条回答 默认 最新

  • dongtidai6519 2018-11-06 10:41
    关注

    fmt.Scan() returns two values and your code expects just one when you call it.

    The Scan signature func Scan(a ...interface{}) (n int, err error) returns first the number of scanned items and eventually an error. A nil value in the error position indicates that there was no error.

    Change your code like this:

    addendOne, err := fmt.Scan()
    if err != nil {
        //Check your error here
    }
    
    fmt.Println("Enter another number: ")
    addendTwo, err := fmt.Scan()
    if err != nil {
        //Check your error here
    }
    

    If you really want to ignore the errors you can used the blank identifier _:

    addendOne, _ := fmt.Scan()
    
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀