可变变量“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
}
有关讨论,请参阅此博客.
这篇关于可变变量“i"的使用方式无效.?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文