如何检查引用是否为null或非null

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

How to check if a reference is null or not

问题

我有一个创建order的函数。我需要知道Ogrn字段是否为空。我应该如何做?

函数:

func CreateOrder(c *gin.Context) {
	var order models.Order
	var form models.Form
	if &form.Ogrn == nil {
		...
	} else {
		...
	}
	c.JSON(http.StatusOK, gin.H{
		...})
}

结构体:

type Form struct {
	gorm.Model
	...
	Ogrn string `json:"ogrn"`
	...
}
英文:

I have a function that creates an order.
I need to know the Ogrn field is null or not. How should I do it?

Func:

func CreateOrder(c *gin.Context) {
	var order models.Order
	var form models.Form
	if &form.Ogrn == nil {
		...
	} else {
		...
	}
	c.JSON(http.StatusOK, gin.H{
		...})
}

Struct:

type Form struct {
	gorm.Model
	...
	Ogrn string `json:"ogrn"`
	...
}

答案1

得分: 2

在你的Form结构体上,Ogrn属性是一个string类型,所以你不能检查它是否为nil

你可以检查它是否为空,因为在Go语言中,空字符串是string类型的默认值。或者,你可以将你的结构体修改为Ogrn是一个指向字符串的指针,*string。然后你可以检查它是否为nil

type Form struct {
    ...
    Ogrn *string
}

func CreateOrder(c *gin.Context) {
    var form models.Form

    if form.Ogrn == nil {
        // 当为nil时执行某些操作。
    }
    ...
}
英文:

As the Ogrn property on your Form struct is a string, you can't check to see if it's nil.

You can either check to see if it's empty as that is the string types default value in Go. Or, you can change your struct so Ogrn is a pointer to a string, *string. You can then check to see if it's nil.

type Form struct {
    ...
    Ogrn *string
}

func CreateOrder(c *gin.Context) {
    var form models.Form

    if form.Ogrn == nil {
        // Do something when nil.
    }
    ...
}

huangapple
  • 本文由 发表于 2022年7月20日 21:36:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/73052656.html
匿名

发表评论

匿名网友

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

确定