【问题标题】:How to check for &{<nil> } in golang [duplicate]如何在 golang 中检查 &{<nil> } [重复]
【发布时间】:2022-01-12 14:50:49
【问题描述】:

我正在尝试从 db 查询中检查结构是否为 nil,但它不起作用。 fmt.Println(loginResponse) //&amp;{&lt;nil&gt; }

if !reflect.ValueOf(loginResponse).IsNil() { // Its not working

        response := models.Response{
            Message: "Login Success",
            Success: true,
            Output:  token,
        }
        return c.JSON(response)

    } 


if !reflect.ValueOf(loginResponse).IsZero() { // its also not working

        response := models.Response{
            Message: "Login Success",
            Success: true,
            Output:  token,
        }
        return c.JSON(response)

    } 

这两个条件都不行。请帮忙

登录响应

type LoginResponse struct {
    Id          interface{} `json:"_id,omitempty" bson:"_id,omitempty"`
    Email       string      `json:"email"`
    Gender      string      `json:"gender"`
    PhoneNumber string      `json:"phonenumber"`
}

【问题讨论】:

  • 显示loginResponse是什么?
  • 如果你传递的是一个指向结构体的指针,它包含一个 nil 指针 (&amp;something{nil}),它与传递一个 nil 指针 (nil) 不同。
  • 是的,但是如何检查呢?
  • 你在检查结构的零值吗?见How to check for an empty struct?

标签: go


【解决方案1】:

尝试这样做,希望它有效

if (LoginResponse{}) != *loginResponse { // as your getting address so derferencing the pointer to struct

        response := models.Response{
            Message: "Login Success",
            Success: true,
            Output:  token,
        }
        return c.JSON(response)

    }

【讨论】:

    猜你喜欢
    • 2021-11-16
    • 2018-03-30
    • 2015-09-23
    • 2016-10-12
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多