组装一个字符串并返回它与 l 系统的生命周期参数

Assembling a string and returning it with lifetime parameters for a l-system

我正在尝试实现 L-System 结构,但遇到了困难。我已经尝试过不同的方法,但我的主要困难来自于参考文献的生命周期。我想要实现的是将应用公理的值传递回我的系统变量,我在 apply_axioms_once.

中传递了必要的生命周期
use std::collections::HashMap;

struct LSytem<'a> {
    axioms: HashMap<&'a char, &'a str>,
}

impl<'a> LSytem<'a> {

    fn apply_axioms_once(&mut self, system: &'a mut str) -> &'a str {
        let mut applied: String = String::new();

        for c in system.chars() {
            let axiom = self.axioms.get(&c).unwrap();

            for s in axiom.chars() {
                applied.push(s);
            }
        }
        system = applied.as_str();
        system 
    }

    fn apply_axioms(&mut self, system: &'a str, iterations: u8) -> &'a str {
        let mut applied: &str = system;

        // check for 0?
        for _ in 0..iterations {
            applied = self.apply_axioms_once(applied);
        }
        &applied
    }
}

我已经阅读了几个类似的问题,但仍然无法完全理解。似乎最切题的答案是 ,但我仍然对如何将其应用到我的问题感到困惑。

我还是 Rust 的初学者,比我想象的要血腥得多。

这行不通,因为您 return 对函数内部创建的数据的引用(因此给定数据的生命周期到函数作用域结束为止,returned 引用将指向任何内容。

您应该尝试从您的函数中 return 字符串,这样 returned 数据就可以拥有了。

我做了这个例子来尝试一下:

use std::collections::HashMap;

struct LSytem<'a> {
    axioms: HashMap<&'a char, &'a str>,
}

impl<'a> LSytem<'a> {

    fn apply_axioms_once(&mut self, system: &String) -> String {
        let mut applied: String = String::new();

        for c in system.chars() {
            let axiom = self.axioms.get(&c).unwrap();

            for s in axiom.chars() {
                applied.push(s);
            }
        }

        applied 
    }

    fn apply_axioms(&mut self, system: &String, iterations: u8) ->String{
        let mut applied = String::from(system);

        // check for 0?
        for _ in 0..iterations {
            applied = self.apply_axioms_once(system);
        }
        applied
    }
}

fn main() {
    let mut ls = LSytem {axioms: HashMap::new()};
    ls.axioms.insert(&'a', "abc");
    let s = String::from("a");
    ls.apply_axioms(&s,1);
}