I am trying to get a map out of the reference and the assertion seems to be failing:
session.AddFlash(gin.H{
"username": username,
"password": password,
}, "_post")
...
flashes := session.Flashes("_post")
if flashes != nil {
flash = flashes[0]
fmt.Printf("%T
", flash)
if post_data, ok := flash.(gin.H); ok {
fmt.Println("post_data:", post_data)
data = post_data
} else {
fmt.Println("post_data(failed):", post_data)
}
}
However I always get the following output, which the assert fails:
*gin.H
post_data(failed): map[]
I assume its due to the assertion I am doing so I've tried:
if post_data, ok := (*flash).(gin.H); ok {
But then I get invalid indirect of flash (type interface {})
I have also tried:
if post_data, ok := *flash.(gin.H); ok {
But that gives me invalid indirect of flash.(gin.H) (type gin.H)
You're putting the *
at the wrong place. It should be flash.(*gin.H)
.
Type assertions require the type you want to assert to be of the exact same type of the assertion part.
From your code, flash
is a type interface{}
, and the underlying type is *gin.H
(printed by fmt.Printf("%T", flash)
). Therefore the assertion should be flash.(*gin.H)
Here are a few examples about of to use type assertions:
package main
import r "reflect"
type A struct {
Name string
}
func main() {
// No pointer
aa := A{"name"}
var ii interface{} = aa
bb := ii.(A)
// main.A
// Pointer
a := &A{"name"}
var i interface{} = a
b := *i.(*A)
// main.A
c := i.(*A)
// *main.A
d := r.Indirect(r.ValueOf(i)).Interface().(A)
// main.A
}
}