<分区>
type MyStruct struct {
IsEnabled *bool
}
如何更改 *IsEnabled = true 的值
这些都不起作用:
*(MyStruct.IsEnabled) = true
*MyStruct.IsEnabled = true
MyStruct.*IsEnabled = true
标签 go
<分区>
type MyStruct struct {
IsEnabled *bool
}
如何更改 *IsEnabled = true 的值
这些都不起作用:
*(MyStruct.IsEnabled) = true
*MyStruct.IsEnabled = true
MyStruct.*IsEnabled = true
最佳答案
您可以通过将 true 存储在内存位置然后访问它来实现此目的,如下所示:
type MyStruct struct {
IsEnabled *bool
}
func main() {
fmt.Println("Hello, playground")
t := true // Save "true" in memory
m := MyStruct{&t} // Reference the location of "true"
fmt.Println(*m.IsEnabled) // Prints: true
}
来自docs :
Named instances of the boolean, numeric, and string types are predeclared. Composite types—array, struct, pointer, function, interface, slice, map, and channel types—may be constructed using type literals.
由于 bool 值是预先声明的,您不能通过复合文字创建它们(它们不是复合类型)。 bool
类型有两个 const
值 true
和 false
。这排除了以这种方式创建文字 bool 值:b := &bool{true}
或类似方式。
应该注意的是,将 *bool 设置为 false
要容易得多,因为 new()
会将 bool 初始化为该值。因此:
m.IsEnabled = new(bool)
fmt.Println(*m.IsEnabled) // False
关于go - 在结构中引用 bool 值进行赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32364027/
相关文章:
go - 使用 part.Read 每 block 读取超过 4096 字节
pointers - 如何在go中定义一个指针,然后将这个指针传递给一个func来改变它的值?
google-app-engine - Appengine 搜索语言
sqlite - mattn/go-sqlite 3's regexp extension faster than sqlite3' s LIKE 运算符是否用于 '%word%' 搜索?
mongodb - 在 golang 中使用全局 mongo (mgo) 数据库有什么缺点?
docker - 如何避免找不到包 "github.com/golang/protobuf/jsonpb"错误