Compilation error that I don't understand


(Alain Van Vynckt ) #1

Hi,

I am new to Go but I don’t understand what’s wrong with my source code below.

I always get a message “13:6: guess declared and not used” ?!?!

Can somebody tell why?

Thanks!

Alain

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)

}


(Lutz Horn) #2

I’ve put your question onto the Go Playground. If you try to run the code, the compiler will tell you that line 14

var guess int

declares guest which you never use in your code except assigning to it

guess = 2

Since you don’t use guess after this, the compiler complaints.

Either use guess or remove the declaration.


(Alain Van Vynckt ) #3

Hi,

Thank you!

Do you mean that the assignment “guess = 2” is not considered as using the variable guest ???

Alain


(Norbert Melzer) #4

A variable that is never read from after it has been written to, basically has no effect, since all writes to it can be removed without changing the programs output.


(Alain Van Vynckt ) #5

OK, I understand, it makes sense.

But I didn’t know that Go was going that far.

When prototyping a program, it does not help much but I must get used to it. C, Java were not that strict …

Thanks for your help.


(Norbert Melzer) #6

The go compiler uses something as annoying as -Wall -Wpedantic -Werror and you can’t change it.