gpt4 book ai didi

rust - Rust:如何将可变变量传递给函数

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

我的功能很大,在Rust中似乎很难实现。我在借阅检查器时遇到问题,我搜索了StackOverflow和Google,但找不到答案。这可能是重复的,但没有解决方案对我有用

use std::collections::HashMap;

fn add(my: &mut MyStruct) {
let count = my.count.entry("Test".to_string()).or_insert(1.0);
let value = get_custom_val(my, 5.0);
my.final_count = *count / value;
*count = 5.0;
}

fn get_custom_val(my: &MyStruct, offset: f32) -> f32 {
return my.val + offset;
}

struct MyStruct {
count: HashMap<String,f32>,
val: f32,
final_count: f32
}

fn main() {
let mut my = MyStruct {count: HashMap::new(), val: 1.0, final_count: 5.0};
my.count.insert("Test".to_string(), 5.0);
add(&mut my);
}

这是一个非常简单的代码。但是MyStruct实际上有很多HashMap,这些HashMap的条目大约有1000个元素。所以我想让事情更优化。

遇到这个错误,

cannot borrow *my as immutable because it is also borrowed as mutable



看来这是一个非常基本的操作,我无法实现。我已经学习Rust了一个多星期,但还不太了解这个借用方法:(

有人能帮我吗?

有些想法是在 let value...中添加{},但这对我没有用,因为我需要在下一行中输入值。

另外,当我尝试其他操作(例如将 get_custom_val更改为 &mut时,出现以下错误)

cannot borrow *my as mutable more than once at a time

最佳答案

您的add函数应该是(请注意前两行是如何交换的):

fn add(my: &mut MyStruct) {
let value = get_custom_val(my, 5.0);
let count = my.count.entry("Test".to_string()).or_insert(1.0);
my.final_count = *count / value;
*count = 5.0;
}

让我们看看为什么您的旧函数会出错:

fn add(my: &mut MyStruct) {
// you get an Entry for the hashmap which requires a mutable reference to it
let count = my.count.entry("Test".to_string()).or_insert(1.0);
// the mutable reference is still there for the entry
// but this function requires an immutable reference
let value = get_custom_val(my, 5.0);
// the error is thrown on this line because you try to use that mutable reference
my.final_count = *count / value;
*count = 5.0;
}

关于rust - Rust:如何将可变变量传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61817830/

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