gpt4 book ai didi

function - 局部函数访问外部变量

转载 作者:行者123 更新时间:2023-12-03 11:41:33 26 4
gpt4 key购买 nike

A local function in Rust显示了如何制作不访问变量的局部函数。
该函数失败,因为它访问v:

// Assume v takes up 1 GB and is slow to compute
let v = [1,2,3];
fn recursive(x:usize) {
if x - v.len() > 0 {
// do stuff that may involve calling recursive() and change v
recursive(x-1);
}
}
recursive(8);
我该怎么做呢?

最佳答案

最简单的选择是通过(可变)引用将状态传递给递归函数:

let mut v = [1, 2, 3];
fn recursive(v: &mut [i32], x: usize) {
if x - v.len() > 0 {
// do stuff that may involve calling recursive() and change v
recursive(v, x - 1);
}
}
recursive(&mut v, 8);

关于function - 局部函数访问外部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64518920/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com