The mutable variable 'i' is used in an invalid way.?

大城市里の小女人 提交于 2019-12-18 07:58:28

问题


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 '!' 

Code:

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?


回答1:


You can't refer to mutables inside a closure, and that includes such constructs as seq{} and async{} blocks.

You could write

let printProcess = async {
        let i = ref 1
        while true do
            System.Console.WriteLine(!i)
            i := !i + 1
    }

See this blog for some discussion.



来源:https://stackoverflow.com/questions/1480582/the-mutable-variable-i-is-used-in-an-invalid-way

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!