我只能支持gradbot所说的——当我需要突变时,我更喜欢let mutable
.
关于两者之间的实现和差异 -ref
单元格本质上是通过一个非常简单的记录来实现的,该记录包含一个可变记录字段。您可以自己轻松编写它们:
type ref<'T> = // '
{ mutable value : 'T } // '
// the ref function, ! and := operators look like this:
let (!) (a:ref<_>) = a.value
let (:=) (a:ref<_>) v = a.value <- v
let ref v = { value = v }
这两种方法之间的一个显着区别是,let mutable
将可变值存储在堆栈中(作为 C# 中的可变变量),而ref
将可变值存储在堆分配记录的字段中。这可能会对性能产生一些影响,但我没有任何数字......
多亏了这一点,使用的可变值ref
可以被别名 - 这意味着您可以创建两个引用相同可变值的值:
let a = ref 5 // allocates a new record on the heap
let b = a // b references the same record
b := 10 // modifies the value of 'a' as well!
let mutable a = 5 // mutable value on the stack
let mutable b = a // new mutable value initialized to current value of 'a'
b <- 10 // modifies the value of 'b' only!