我下面有接受布尔指针的函数。我想知道是否有任何符号可以让我在struct文字中将is
字段的值设置为true
;基本上不需要定义新的标识符(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){}
您可以这样做,但并非最佳选择:
h := handler{is: &[]bool{true}[0]}
fmt.Println(*h.is) // Prints true
基本上,它创建一个带有bool
value的切片true
,为其第一个元素建立索引并获取其地址。没有创建新的变量,但是有很多样板文件(并且后备数组将保留在内存中,直到第一个元素的地址存在)。
更好的解决方案是编写一个辅助函数:
func newTrue() *bool {
b := true
return &b
}
并使用它:
h := handler{is: newTrue()}
fmt.Println(*h.is) // Prints true
您还可以使用单线匿名功能来做到这一点:
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)}
要查看所有选项,请查看其他答案:如何在Go中执行文字* int64?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句