是否可以在Golang中定义不可变的结构?初始化后,只对struct的字段进行读操作,不修改字段值.如果是这样,该怎么做.
Ale*_*nok 32
通过使其成员不导出并提供读者,可以使结构在包外部是只读的.例如:
package mypackage
type myReadOnly struct {
value int
}
func (s myReadOnly) Value() int {
return s.value
}
func NewMyReadonly(value int) myReadOnly{
return myReadOnly{value: value}
}
Run Code Online (Sandbox Code Playgroud)
用法:
myReadonly := mypackage.NewMyReaonly(3)
fmt.Println(myReadonly.Value()) // Prints 3
Run Code Online (Sandbox Code Playgroud)
Go 中无法定义不可变结构:结构字段是可变的,并且 const 关键字不适用于它们。然而,Go 可以轻松地通过简单的赋值来复制整个结构,因此我们可能认为按值传递参数就足以以复制为代价获得不变性。
然而,毫不奇怪,这不会复制指针引用的值。由于内置集合(映射、切片和数组)是引用并且是可变的,因此复制包含其中之一的结构只是将指针复制到相同的底层内存。
例子 :
type S struct {
A string
B []string
}
func main() {
x := S{"x-A", []string{"x-B"}}
y := x // copy the struct
y.A = "y-A"
y.B[0] = "y-B"
fmt.Println(x, y)
// Outputs "{x-A [y-B]} {y-A [y-B]}" -- x was modified!
}
Run Code Online (Sandbox Code Playgroud)
注意:因此,您必须对此非常小心,如果您按值传递参数,则不要假设不变性。
有一些深度复制库尝试使用(慢速)反射来解决此问题,但由于无法通过反射访问私有字段,因此它们的效果不佳。因此,避免竞争条件的防御性复制将很困难,需要大量样板代码。Go 甚至没有一个可以标准化这一点的 Clone 接口。
信用: https: //bluxte.net/