gpt4 book ai didi

rust - 如何解决 Rust 中的 "returns a value referencing data owned by the current function"错误?

转载 作者:行者123 更新时间:2023-11-29 07:48:30 27 4
gpt4 key购买 nike

我正在尝试编写生成随机表达式的二叉树。我需要随机数和一组函数。我收到一个向量,其中包含树中表达式的函数和深度。在运算符向量中,我还包含一个“ELEM”字符串,用于从向量中选择一个随机元素,然后将其更改为 float 。

借用、移动和所有权的具体用法我好像还是不太明白,既然是递归函数,就报错值已被借用,不能返回局部变量。

use rand::Rng;

struct Expression_Node<'a> {
val: &'a str,
left: Option<Box<Expression_Node<'a>>>,
right: Option<Box<Expression_Node<'a>>>,
}

fn Create_Expression(
operators: Vec<&str>,
p: i32,
) -> std::option::Option<std::boxed::Box<Expression_Node<'_>>> {
if p == 0 {
let value = String::from(rand::thread_rng().gen::<f64>().to_string());
let value2: &str = value.as_ref();
//println!("{:?}", value);
let new_node = Expression_Node {
val: value2,
left: None,
right: None,
};
return Some(Box::new(new_node));
}
let value: &str = *rand::thread_rng().choose(&operators).unwrap();
println!("VAL: {:?}", value);
if value == "ELEM" {
let value = rand::thread_rng().gen::<f64>().to_string();
}

let new_node = Expression_Node {
val: value,
left: Create_Expression(operators.clone(), p - 1),
right: Create_Expression(operators.clone(), p - 1),
};
return Some(Box::new(new_node));
}

错误:

error[E0515]: cannot return value referencing local variable `value`
--> src/lib.rs:22:16
|
15 | let value2: &str = value.as_ref();
| ----- `value` is borrowed here
...
22 | return Some(Box::new(new_node));
| ^^^^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function

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