Detect if custom struct exist in GO

huangapple go评论82阅读模式
英文:

Detect if custom struct exist in GO

问题

有没有办法检查变量中是否存在自定义结构体?不幸的是,在nil检查时我收到了"mismatched types models.Memberz and untyped nil"的消息。

我现在已经将其更改为额外的变量,并在那里更改了类型,看起来可以工作。

以下是使用额外变量的代码,它可以正常工作,但有点繁琐。

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",
    })
}

实际上,我希望下面的代码能够工作,但它会报错。在Golang中是否有其他选项可以检查这个?

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",
    })

}
英文:

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",
	})

}

答案1

得分: 1

使用类型断言时,可以使用特殊的“逗号-OK”赋值形式。

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

注意:在进行类型断言时,除非你确信知道接口中存储的正确类型,否则应始终使用“逗号-OK”赋值形式,因为如果你不使用“逗号-OK”并且不确定类型,那么你的程序很可能会在早期或晚期崩溃。使用普通赋值形式的错误类型断言会导致运行时恐慌。


你也可以在if语句内部进行类型断言,以使代码更紧凑,只需记住此时变量的作用域仅限于if块及其else块,外部无法访问。

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",
    })

}
英文:

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",
    })

}

huangapple
  • 本文由 发表于 2023年1月11日 18:33:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75081643.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定