我正在尝试对生成随机表达式的二叉树进行编码。我需要随机数和一组函数。我收到一个向量,其中包含树中表达式的功能和深度。在运算符向量中,我还包括一个“ ELEM”字符串,该字符串用于从向量中选择一个随机元素,然后将其更改为浮点型。
似乎我仍然不了解借用,移动和所有权的确切用途,因为它是递归函数,它显示错误,指出值已借用并且无法返回局部变量。
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 { …Run Code Online (Sandbox Code Playgroud) 在Rust中,有没有办法处理运算符函数,如add或sub?我需要获得这些函数的参考,但我只能找到特征.我将在这里留下我在Python中需要的比较(如包装器方法).
A = 1
B = 2
A.__add__(B)
#Or maybe do something more, like
C = int(1).__add__
C(2)
Run Code Online (Sandbox Code Playgroud) 我有一个文件,需要逐行读取并分成两个句子,并用“=”分隔。我正在尝试使用迭代器,但我找不到如何在split. 文档说std::str::Split实现了该特征,但我仍然不知道如何使用它。
use std::{
fs::File,
io::{prelude::*, BufReader},
};
fn example(path: &str) {
for line in BufReader::new(File::open(path).expect("Failed at opening file.")).lines() {
let words = line.unwrap().split("="); //need to make this an iterable
}
}
Run Code Online (Sandbox Code Playgroud)
我如何使用我知道已经实现为 split 之类的特征?