我试图在F#中编写一些简单的代码,我得到这个错误:
Error 1 The mutable variable 'i' is used in an invalid way. Mutable variables may not be captured by closures. Consider eliminating this use of mutation or using a heap-allocated mutable reference cell via 'ref' and '!'
Run Code Online (Sandbox Code Playgroud)
码:
let printProcess = async {
let mutable i = 1;
while true do
System.Console.WriteLine(i);//error is here
i <- i + 1;
}
Run Code Online (Sandbox Code Playgroud)
为什么不让它打印变量?
Bri*_*ian 17
您不能在闭包内引用mutable,并且包括seq {}和async {}块等构造.
你可以写
let printProcess = async {
let i = ref 1
while true do
System.Console.WriteLine(!i)
i := !i + 1
}
Run Code Online (Sandbox Code Playgroud)
有关讨论,请参阅此博客.