如何在结构文字中将布尔指针设置为true? [英] How to set bool pointer to true in struct literal?
问题描述
我有一个下面的函数,该函数接受一个布尔指针.我想知道是否有任何符号可以让我在结构文字中将 is
字段的值设置为 true
;基本上不需要定义新的标识符(即var x:= true; handler {is:& x})
I have the function below which accepts a bool pointer. I'm wondering if there is any notation which allows me to set the value of the is
field to true
in the struct literal; basically without to define a new identifier (i.e. var x := true ; handler{is: &x} )
package main
import "fmt"
func main() {
fmt.Println("Hello, playground")
check(handler{is: new(bool) })
}
type handler struct{
is *bool
}
func check(is handler){}
推荐答案
您可以这样做,但这不是最佳选择:
You can do that but it's not optimal:
h := handler{is: &[]bool{true}[0]}
fmt.Println(*h.is) // Prints true
基本上,它会创建一个切片,该切片具有一个值为 true
的 bool
,索引其第一个元素并获取其地址.没有创建新的变量,但是有很多样板文件(并且后备数组将保留在内存中,直到第一个元素的地址存在).
Basically it creates a slice with one bool
of value true
, indexes its first element and takes its address. No new variable is created, but there is a lot of boilerplate (and backing array will remain in memory until the address to its first element exists).
更好的解决方案是编写一个辅助函数:
A better solution would be to write a helper function:
func newTrue() *bool {
b := true
return &b
}
并使用它:
h := handler{is: newTrue()}
fmt.Println(*h.is) // Prints true
您还可以使用单线匿名功能来做到这一点:
You can also do it with a one-liner anonymous function:
h := handler{is: func() *bool { b := true; return &b }()}
fmt.Println(*h.is) // Prints true
或变体形式:
h := handler{is: func(b bool) *bool { return &b }(true)}
To see all your options, check out my other answer: How do I do a literal *int64 in Go?
这篇关于如何在结构文字中将布尔指针设置为true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!