I am using the declared variable to return a struct. Why is the compiler says I'm not using the declared variable?
I put log.Printf statements to help debug the error. Why doesn't the log.Printf count as using the variable?
import (
"github.com/gorilla/sessions"
)
func profileFromSession(r *http.Request) *workout.Athlete {
session, err := workout.SessionStore.Get(r, defaultSessionID)
log.Printf("$$$$$$$$$$$ session contains %#v", session)
if err != nil {
log.Print("$$$$$$$$ error SessionStore.Get %s", err)
return nil
}
// retrieve Athlete struct and type-assert it.
valAthlete := session.Values[currentAthleteKey]
var athlete = &workout.Athlete{}
log.Printf("before type check athlete is %T", athlete)
if athlete, ok := valAthlete.(*workout.Athlete); !ok {
log.Print("athlete is not the correct Type")
}
log.Printf("profile athlete has %#s", athlete)
return athlete
}
ERROR 2019-07-26 22:00:32,931 instance_factory.py:243] Failed to build Go application
/var/folders/mw/0y88j8_54bjc93d_lg3120qw0000gp/T/tmpAqfXoRappengine-go-bin/auth.go:265:33: athlete declared and not used
Using dev_appserver.py go version go1.11.2 darwin/amd64
The :=
statement declares a new variable. In particular, variables declared using :=
within an if
condition are scoped to only the corresponding if
and else
blocks, not the rest of the surrounding scope.
So you have two distinct athlete
variables there: one scoped to the function, and a second one scoped to the if
-statement within that function.
To assign to the function-scoped variable instead of declaring a new local variable, use =
instead of :=
. In order to do that, you may need to also declare the ok
variable ahead of that assignment:
var ok bool
if athlete, ok = valAthlete.(*workout.Athlete); !ok {
See also https://golang.org/issue/31064 and https://golang.org/issue/377.