Home > Software engineering >  How to check if a reference is null or not
How to check if a reference is null or not

Time:07-21

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"`
    ...
}

CodePudding user response:

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.
    }
    ...
}
  • Related