为什么在 Go 中,除非我在结构体中使用指针,否则 JSON 验证会抛出错误?

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

Go - JSON validation throwing error unless I use pointer in the struct. Why?

问题

这是我的验证结构:

type PostEmail struct {
	Username       string `json:"username" validate:"required"`
	Email          string `json:"email" validate:"required"`
	IsRefreshEmail *bool  `json:"isRefreshEmail" validate:"required"`
}

我用 *bool 来指向 IsRefreshEmail 的值。如果我移除指针并且在调用API时没有它,API会抛出语法错误。
只有当布尔值为 false 时才会发生这种情况。如果它是 true,即使你移除指针,API也会正确响应。

为什么会这样?这是正常的吗?我无法理解,也不知道我是否在使用指针时出错。我唯一确定的是,如果我从 bool 中移除 *,并且在Postman中为 isRefreshEmail 字段插入 false 值,API会抛出异常。

有人可以解释一下吗?谢谢。

英文:

Here is my validation structure:

type PostEmail struct {
	Username       string `json:"username" validate:"required"`
	Email          string `json:"email" validate:"required"`
	IsRefreshEmail *bool  `json:"isRefreshEmail" validate:"required"`
}

I'm pointing the value of IsRefreshEmail with *bool. If I remove the pointer and I try to call my API without it, the API will throw a bad syntax error.
That will happen only if the boolean value will be false. If it's true even if you remove the pointer the API will respond correctly.

Why is this happening? It's normal? I can't understand it and i don't even know if I'm doing it wrong with the pointer. What I surely know is that if I remove the * from bool and I insert false as value in postman for the field isRefreshEmail the API will throw an exception.

Someone can explain please? Thank you.

答案1

得分: 3

一个布尔值可以表示两个值,falsetrue

var IsRefreshEmail bool

一个布尔指针可以表示三个值,falsetruenil

var IsRefreshEmail *bool

这样做的好处是,你可以将falsenil进行比较:

{"email": "hello", "isRefreshEmail": false}
{"email": "hello"}

如果没有指针,上述两个JSON在解析后将完全相同。
根据你的情况,你可能不关心这一点。然而,如果你需要知道值是否被省略,则需要使用指针。

英文:

A boolean can represent two values, false or true:

var IsRefreshEmail bool

A boolean pointer can represent three values, false, true or nil:

var IsRefreshEmail *bool

The benefit of this, is that you can compare false with nil:

{"email": "hello", "isRefreshEmail": false}
{"email": "hello"}

without the pointer, the two JSON above will be identical after Unmarshal.
Depending on your situation, you might not care about that. However if you need
to know if the value was omitted, then pointer is required.

答案2

得分: 2

布尔类型的默认值是false

指针类型的布尔默认值是nil

因此,当使用指针类型并且发送的值为false时,结果是false

但是当使用布尔类型并发送false时,需要进行检查并将其视为验证失败(与默认值相同)

对于整数类型和指针类型的整数,默认值都是0

英文:

Default value of bool is false

Default value of *bool is nil

So when using with pointer and the value you send is false -> fasle

But when use with bool -> you send false -> validate with check and make it failure validation(same as default value)

The problem is same for int and *int with the 0 value

huangapple
  • 本文由 发表于 2022年7月22日 07:15:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/73073571.html
匿名

发表评论

匿名网友

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

确定