Golang编译错误问题求解
Golang编译错误问题求解 你好,
我是Go语言的新手,但我不明白下面的源代码有什么问题。
我总是收到消息"13:6: guess declared and not used"?!?!
有人能告诉我原因吗?
谢谢!
package main
import (
"fmt"
"math/rand"
)
const maxNumber = 10
func main() {
var number int
var guess int
var attemps int
// Generate a random number to guess
number = rand.Intn(10) + 1
// Prompt for number to guess
guess = 2
// Congrats
fmt.Printf("Great! You found the number %v in %v attemps!", number, attemps)
}
更多关于Golang编译错误问题求解的实战教程也可以访问 https://www.itying.com/category-94-b0.html
你好,
谢谢!
你的意思是赋值语句"guess = 2"不被视为使用了变量guess吗?
更多关于Golang编译错误问题求解的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
一个在写入后从未被读取的变量基本上没有任何作用,因为所有对它的写入操作都可以在不改变程序输出的情况下被移除。
Go 编译器使用了类似于 -Wall -Wpedantic -Werror 这样令人烦恼的选项,而且你无法更改它。
func main() {
fmt.Println("hello world")
}
好的,我明白了,这很合理。
但我不知道 Go 在这方面要求这么严格。
在程序原型设计阶段,这确实帮助不大,但我必须习惯它。C、Java 都没有这么严格……
感谢你的帮助。
我已将您的问题发布到 Go Playground。如果您尝试运行代码,编译器会提示第14行
var guess int
声明了 guess 变量,但您在代码中从未使用它——除了给它赋值
guess = 2
由于在此之后您没有使用 guess,所以编译器会报错。
请使用 guess 变量或删除该声明。
这个编译错误是因为你在代码中声明了变量 guess 但从未使用它。Go 编译器要求所有声明的变量都必须被使用,否则会报错。
在你的代码中:
- 第 10 行声明了
var guess int - 第 17 行给
guess赋值guess = 2 - 但之后这个
guess变量再没有被读取或用于任何操作
要解决这个问题,你需要实际使用 guess 变量,比如与随机生成的数字进行比较。
以下是修正后的代码示例:
package main
import (
"fmt"
"math/rand"
)
const maxNumber = 10
func main() {
var number int
var guess int
var attempts int
// Generate a random number to guess
number = rand.Intn(10) + 1
// Prompt for number to guess
guess = 2
attempts = 1
// Check if guess is correct and use the guess variable
if guess == number {
fmt.Printf("Great! You found the number %v in %v attempts!", number, attempts)
} else {
fmt.Printf("Sorry, you guessed %v but the number was %v", guess, number)
}
}
或者,如果你确实不需要 guess 变量,可以删除它的声明和赋值:
package main
import (
"fmt"
"math/rand"
)
const maxNumber = 10
func main() {
var number int
var attempts int
// Generate a random number to guess
number = rand.Intn(10) + 1
attempts = 1
// Congrats
fmt.Printf("Great! You found the number %v in %v attempts!", number, attempts)
}
另外,我注意到你的代码中 attemps 拼写有误,应该是 attempts,这不会导致编译错误但会影响代码可读性。

