【发布时间】:2017-03-11 11:07:24
【问题描述】:
我想要一个调用其他相互递归的函数的函数,但我已经有了类似的类型签名:
fn f1(mut index: &mut usize, ..)
fn f2(mut index: &mut usize, ..)
我真的想要一组相互递归的函数,它们只能改变我在main() 函数中定义的index 变量,并且不能指向任何其他变量。
我已经阅读了来自What's the difference in `mut` before a variable name and after the `:`? 的 2 个答案,并且我尝试了几种方法,但仍然无法实现我想要的。我想我不太了解这些概念。
这是我目前理解的证据:
// with &mut I can change the referred value of n, but then I can't
// pass a mutable reference anywhere
fn mutate_usize_again(n: &mut usize) {
*n += 1;
// n += 70; ^ cannot use `+=` on type `&mut usize`
}
fn mutate_usize_two_times(mut n: &mut usize) {
*n = 8;
// if I don't write mut n, I can't pass a mutable reference to
// the mutate_usize_again function
mutate_usize_again(&mut n);
}
fn mutate_usize_one_time_referred_value(n: &mut usize) {
*n += 25;
}
// this changes the referred value of n
fn mutate_usize_one_time_mutable_pointer(mut n: usize) {
println!("n before assigning in mutate_usize_one_time = {}", n);
n = 48;
println!("n after assigning in mutate_usize_one_time = {}", n);
}
// doesn't work because of lifetimes
// this changes where is pointing a (Copy?) reference of n
// passed value does not change
/*
fn mutate_usize_one_time(mut n: &usize) {
println!("n before assigning in mutate_usize_one_time = {}", n);
n = &48;
println!("n after assigning in mutate_usize_one_time = {}", n);
}
*/
fn main() {
let mut index = 0;
mutate_usize_one_time_mutable_pointer(index);
println!("index after mutate_usize_one_time_mutable_pointer = {}", index);
mutate_usize_two_times(&mut index);
println!("index after mutate_usize_two_times = {}", index);
mutate_usize_one_time_referred_value(&mut index);
println!("index after mutate_usize_ = {}", index);
}
如果我误解了,我将非常感谢对我的代码中发生的事情的一个很好的解释。
我开始认为我想要的已经完成了:
-
index必须引用它的更新值 =>mut index -
index必须能够更改引用的值并将可变引用传递给其他函数。 =>&mut usize - 如果它是另一个具有相同类型
(mut index2: &mut usize)的函数参数,编译器不会让我有 2 个指向同一内存位置的可变引用。
【问题讨论】:
-
你想做什么?修改引用指向的值还是改变引用本身?
-
@TatsuyukiIshi 编辑了关于我的目标的更完整信息
-
@freinn 我猜你还是很困惑。集中注意力,然后试着回忆你的想法并深入研究它们。在你理解一个代码之前,你应该能够一眼就猜到它的作用。我们不能总是帮助你,但我们可以猜测。从您的写作中,我们可以看到您的想法和想法。
-
@VitaliPom question == question => 不知道。 answer == answer => 知识就在那里。
标签: reference rust immutability mutable