可变变量"i"以无效方式使用. [英] The mutable variable 'i' is used in an invalid way.?
本文介绍了可变变量"i"以无效方式使用.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图用F#编写一些简单的代码,但出现此错误:
I am attempting to write some simple code in F#, and i get this error:
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 '!'
代码:
let printProcess = async {
let mutable i = 1;
while true do
System.Console.WriteLine(i);//error is here
i <- i + 1;
}
为什么不让我打印变量?
Why won't it let me print the variable?
推荐答案
您不能在闭包内部引用可变项,而可变项包括诸如seq {}和async {}块之类的构造.
You can't refer to mutables inside a closure, and that includes such constructs as seq{} and async{} blocks.
你可以写
let printProcess = async {
let i = ref 1
while true do
System.Console.WriteLine(!i)
i := !i + 1
}
有关某些讨论,请参见此博客.
See this blog for some discussion.
这篇关于可变变量"i"以无效方式使用.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文