Home > database >  Detect if custom struct exist in GO
Detect if custom struct exist in GO

Time:01-12

Is there a way to check if the custom struct exists in the variable? Unfortunately, at the nil check I get the message "mismatched types models.Memberz and untyped nil" ?

I have now changed it to an extra variable and changed the type there and that seems to work.

This is the code that works with an extra variable and works properly but finds it a bit cumbersome.

func Session(c *gin.Context) {
    session := sessions.Default(c)

    v := session.Get("secure")

    if v == nil {

        var data = models.Memberz{
            Name:     "test",
            Age:      0,
            Loggedin: true,
        }

        session.Set("secure", data)
        session.Save()
    } else {

        member := v.(models.Memberz)
        fmt.Println("data: "   member.Name)
    }
    c.JSON(200, gin.H{
        "status": "success",
    })
}

I was actually hoping that this code below would work, but it gives an error. Is there any other option within Golang how I could check this?

func Session(c *gin.Context) {
    session := sessions.Default(c)

    v := session.Get("secure").(models.Memberz)

    if v == nil {

        var data = models.Memberz{
            Name:     "test",
            Age:      0,
            Loggedin: true,
        }

        session.Set("secure", data)
        session.Save()
    } else {

        fmt.Println("data: "   v.Name)
    }

    c.JSON(200, gin.H{
        "status": "success",
    })

}

CodePudding user response:

Use the special "comma ok" form of assignment that is available to type assertions.

v, ok := session.Get("secure").(models.Memberz)
if !ok {
    // ...
} else {
    // ...
}

NOTE: when doing type assertions, you should always use the "comma ok" form of assignment unless you are 100% sure you know the correct type that's stored in the interface, because if you don't do "comma ok" and you don't know the type for sure, then your program is likely to crash sooner or later. An incorrect type assertion that uses the normal form of assignment causes a runtime panic.


You can also do the type assertion inside the if-statement to make the code more compact, just keep in mind that then the variable is scoped to the if block and its else block, it will not be accessible outside.

func Session(c *gin.Context) {
    session := sessions.Default(c)

    if v, ok := session.Get("secure").(models.Memberz); !ok {
        var data = models.Memberz{
            Name:     "test",
            Age:      0,
            Loggedin: true,
        }

        session.Set("secure", data)
        session.Save()
    } else {
        fmt.Println("data: "   v.Name)
    }

    c.JSON(200, gin.H{
        "status": "success",
    })

}
  • Related