Golang中如何正确初始化指针为true

Golang中如何正确初始化指针为true 我有一个如下形式的JSON结构体:

type postJSON struct {
	ButtonA *bool `json:"button_a,omitempty"`
	ButtonB *bool `json:"button_b,omitempty"`
}

这允许我在发送的消息中省略false值,即只发送true值。

目前,我必须像这样设置一个(包)变量:

var pressed = new(bool)
...
	post_json := postJSON{}
	if strings.Contains(msg, "a") {
		post_json.ButtonA = pressed
	}
...

func init() {
	*pressed = true
}

有没有更好的方法来设置pressed变量——或者更好的处理方式?我真正想要的是类似这样的写法:

post_json.ButtonA = &true

注意:我不想每次都(新建)一个指向布尔值true的新指针——所以创建并赋值(我认为)不是一个好的解决方案。

谢谢 - Andy


更多关于Golang中如何正确初始化指针为true的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

我会移除所有 *bool 的复杂处理,改为将字段设为 bool 类型,并为 postJSON 添加自定义的序列化方法,使其理解 false 值应被省略。这将使结构体更易于使用。

更多关于Golang中如何正确初始化指针为true的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go中,你可以使用几种更优雅的方式来初始化指向true的指针,避免使用包变量和init()函数。以下是几种推荐的方法:

方法1:使用辅助函数(最推荐)

func BoolPtr(b bool) *bool {
    return &b
}

// 使用方式
postJSON := postJSON{}
if strings.Contains(msg, "a") {
    postJSON.ButtonA = BoolPtr(true)
}

方法2:使用预定义的变量

var (
    truePtr  = func() *bool { b := true; return &b }()
    falsePtr = func() *bool { b := false; return &b }()
)

// 使用方式
postJSON := postJSON{}
if strings.Contains(msg, "a") {
    postJSON.ButtonA = truePtr
}

方法3:使用结构体方法

type postJSON struct {
    ButtonA *bool `json:"button_a,omitempty"`
    ButtonB *bool `json:"button_b,omitempty"`
}

func (p *postJSON) SetButtonA(b bool) {
    if p.ButtonA == nil {
        p.ButtonA = new(bool)
    }
    *p.ButtonA = b
}

func (p *postJSON) SetButtonB(b bool) {
    if p.ButtonB == nil {
        p.ButtonB = new(bool)
    }
    *p.ButtonB = b
}

// 使用方式
postJSON := postJSON{}
if strings.Contains(msg, "a") {
    postJSON.SetButtonA(true)
}

方法4:使用工厂函数

func NewPostJSON() postJSON {
    return postJSON{
        ButtonA: nil,
        ButtonB: nil,
    }
}

func WithButtonA(b bool) func(*postJSON) {
    return func(p *postJSON) {
        p.ButtonA = &b
    }
}

func WithButtonB(b bool) func(*postJSON) {
    return func(p *postJSON) {
        p.ButtonB = &b
    }
}

// 使用方式(函数式选项模式)
postJSON := NewPostJSON()
if strings.Contains(msg, "a") {
    WithButtonA(true)(&postJSON)
}

方法5:单行内联初始化(Go 1.18+)

postJSON := postJSON{}
if strings.Contains(msg, "a") {
    postJSON.ButtonA = func() *bool { b := true; return &b }()
}

推荐使用方法1,因为它:

  1. 代码简洁清晰
  2. 可重用
  3. 类型安全
  4. 避免了包变量的全局状态

如果你需要在多个地方使用,可以将BoolPtr函数放在一个公共的util包中:

// util/pointers.go
package util

func BoolPtr(b bool) *bool {
    return &b
}

func StringPtr(s string) *string {
    return &s
}

func IntPtr(i int) *int {
    return &i
}
回到顶部