简体   繁体   English

类型断言落在引用/指针上

[英]Type assertion falling on reference / pointer

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\n", 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 {}) 但是然后我得到了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) 但这给了我invalid indirect of flash.(gin.H) (type gin.H)

You're putting the * at the wrong place. 您将*放在错误的位置。 It should be flash.(*gin.H) . 它应该是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) ). 从您的代码中, flash是类型interface{} ,而基础类型是*gin.H (由fmt.Printf("%T", flash)打印)。 Therefore the assertion should be flash.(*gin.H) 因此该断言应该是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
}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM