Golang中无法作为值使用的解决方法

Golang中无法作为值使用的解决方法 运行 go run 时,我遇到了以下错误:

.\copyres.go:76:50: syntax error: cannot use destsize := destinationstat.Size() as value

我知道这很烦人。通常我能看出来并解决它,但这次我看不出来。

这里是一个代码片段:

destinationstat, err := os.Stat(tofile)
if err == null
destsize := destinationstat.Size()
if destsize != nosize {
retry = false
}
}

非常感谢任何帮助。我确信问题很小。正如我所说,我看不出来,这快把我逼疯了。


更多关于Golang中无法作为值使用的解决方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

谢谢。我想是熬了太多夜,才没注意到这一点。

更多关于Golang中无法作为值使用的解决方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


chrisleahy:

if err == null

你好 @chrisleahy,这一行缺少一个花括号。原始代码中也缺少吗?这可能是导致错误信息的原因。

从错误信息来看,问题在于你试图将 destsize := destinationstat.Size() 这个赋值语句当作值来使用。在Go语言中,短变量声明(:=)是一个语句,不能作为表达式使用。

在你的代码片段中,错误很可能出现在第76行,你试图在需要值的地方使用了赋值语句。例如,你可能在函数调用或表达式中这样写了:

// 错误示例
someFunction(destsize := destinationstat.Size())

// 或
if destsize := destinationstat.Size() != nosize {
    // ...
}

正确的做法应该是:

// 正确示例1:先赋值,再使用
destsize := destinationstat.Size()
someFunction(destsize)

// 正确示例2:在if语句中正确使用
if destsize := destinationstat.Size(); destsize != nosize {
    retry = false
}

根据你提供的代码片段,我猜测你的实际代码可能是这样的:

// 错误写法
if destsize := destinationstat.Size() != nosize {
    retry = false
}

应该改为:

// 正确写法
if destsize := destinationstat.Size(); destsize != nosize {
    retry = false
}

另外,我还注意到你代码片段中的几个问题:

  1. if err == null 应该是 if err == nil
  2. 缺少大括号

完整修正后的代码应该是:

destinationstat, err := os.Stat(tofile)
if err == nil {
    if destsize := destinationstat.Size(); destsize != nosize {
        retry = false
    }
}

检查你的第76行代码,确保没有在需要表达式的地方使用赋值语句。

回到顶部