You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
as you see, logLevel var is changed in the conditional blocks base on whether there is an environment variable set for it. But the compiler gives an error: logLevel declared and not used
The error is addressing the inner inner block when an environment var is set, but can not be processed.
What did you expect to see?
I expected the code to be compiled without the error
What did you see instead?
the error
The text was updated successfully, but these errors were encountered:
Both the inner logLevel and err variables are new declared variable.
The inner logLevel shadows the outer one.
This is a famous trap many new Gophers will encounter.
funcmain() {
varlogLevelLogLevel=LogLevelDebuglogLevelStr, isSet:=os.LookupEnv("POSTGRES_LOG_LEVEL")
ifisSet {
// The logLevel is a new declared varlogLevel, err:=LogLevelFromString(logLevelStr)
iferr!=nil {
logLevel=LogLevelDebug
}
}
config:=Config{LogLev: logLevel}
fmt.Println(config)
}
the logLevel, err := LogLevelFromString(logLevelStr) line declares a brand-new logLevel which scope is limited to the if isSet { block. This is because := (that you are using because you need a new err) will always create new variables when used in the multiple assignment form a, b, c ... := .
Basically the logLevel, err := LogLevelFromString(logLevelStr) line is not setting the var logLevel that you declared at line 10, it's creating a new one. That one is not used. So the compiler error is correct.
To fix this, you can pre-declare err and then write
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
it IS the lates release
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
I'm using pgx package to work with postgres. but I copied needed code to reproduce the error without any dependencies
go play ground
as you see, logLevel var is changed in the conditional blocks base on whether there is an environment variable set for it. But the compiler gives an error:
logLevel declared and not used
The error is addressing the inner inner block when an environment var is set, but can not be processed.
What did you expect to see?
I expected the code to be compiled without the error
What did you see instead?
the error
The text was updated successfully, but these errors were encountered: