This question already has an answer here:
I'm new for golang, this is my program:
func main() {
checkParam(os.Args)
var got,bj,ll float32
var dur int
var err error
if bj, err := strconv.ParseFloat(os.Args[1], 32); err != nil {
usageExit()
}
if ll, err := strconv.ParseFloat(os.Args[2], 32); err != nil {
usageExit()
}
if dur, err := strconv.Atoi(os.Args[3]); err != nil {
usageExit()
}
for i := 0; i < dur; i++ {
got := bj * (1.0 + ll)
}
fmt.Print("Result: %f", got)
_ = got
_ = bj
_ = ll
_ = dur
_ = err }
But I got errors while running:
gateway@gateway-virtual-machine:basic$ go run fulijisuan.go
command-line-arguments
./fulijisuan.go:27:47: bj declared and not used
./fulijisuan.go:31:47: ll declared and not used
./fulijisuan.go:35:38: dur declared and not used
./fulijisuan.go:40:22: got declared and not used
In My opinion, I define err/bj/ll/fur/got above, and then use these value to accept Args.
Why I got error? I think I already use these values.
Fix it already, replace := into = .
</div>
You correctly defined variables but you have not used them. Use them or at least assign to _
.
_ = err
In most programming languages you will get at most a warning for having unused variable. Go enforces using every declared variable and will stop compilation with the error you just came across.
By using :=
in the if
block scope you declared new variables with the same names but not used the new ones in that scope.
In Golang FAQ section the reason for an error of unused variable is mentioned:
The presence of an unused variable may indicate a bug, while unused imports just slow down compilation, an effect that can become substantial as a program accumulates code and programmers over time. For these reasons, Go refuses to compile programs with unused variables or imports, trading short-term convenience for long-term build speed and program clarity.
The variables you have declared should be used in your program at block level inside main scope. that's why the error
func main() {
checkParam(os.Args)
var got,bj,ll float32
var dur int
var err error
if bj, err := strconv.ParseFloat(os.Args[1], 32); err != nil {
usageExit()
}
fmt.Println(bj) // use declared variables in your program
}
If you really wants to skip a variable like err
you can use _
it like below
bj, _ := strconv.ParseFloat(os.Args[1], 32)