Rust 锈蚀寿命说明符的问题
考虑以下计划:Rust 锈蚀寿命说明符的问题,rust,lifetime,Rust,Lifetime,考虑以下计划: fn func(source: &str, state: & Vec<&str>) { println!("{}", source); println!("{}", state[0]); } fn step<'a>(source: &'a str, state: &mut Vec<&'a str>) { state.push(&source[4..10]);
fn func(source: &str, state: & Vec<&str>) {
println!("{}", source);
println!("{}", state[0]);
}
fn step<'a>(source: &'a str, state: &mut Vec<&'a str>) {
state.push(&source[4..10]);
func(source, state);
state.push(&source[4..10]);
}
fn main() {
let source = "abcdefghijklmnopqrstuvwxyz";
{
let mut state = Vec::<&str>::new();
step(source, &mut state);
step(source, &mut state);
step(source, &mut state);
}
}
如果有人能告诉我怎么做,我将不胜感激
注意:在这个示例程序中,“source”是一个具有静态生存期的字符串。在“真实”程序中,“源”没有静态生存期,而是程序在运行时读取的文件内容。“源”的寿命等于或长于“状态”函数参数的寿命情况如下:
fn step<'a>(source: &'a str,
state: &mut Vec<&'a str>)
struct MyStruct<'a, 'b> {
pub source: &'a str,
pub state: &'b mut Vec<&'b str>,
}
fn func(arg: MyStruct) {
println!("{}", arg.source);
println!("{}", arg.state[0]);
}
fn step<'a>(source: &'a str,
state: &mut Vec<&'a str>) {
state.push(&source[4..10]);
let s = MyStruct{source: source, state: state};
func(s);
state.push(&source[4..10]);
}
fn main() {
let source = "abcdefghijklmnopqrstuvwxyz";
{
let mut state = Vec::<&str>::new();
step(source, &mut state);
step(source, &mut state);
step(source, &mut state);
}
}
107 | state: &mut Vec<&'a str>) {
| ----- consider changing the type of `state` to `&'a mut std::vec::Vec<&'a str>`
108 | state.push(&source[4..10]);
109 | let s = MyStruct{source: source, state: state};
| ^^^^^ lifetime `'a` required
117 | step(source, &mut state);
| ----- first mutable borrow occurs here
118 | step(source, &mut state);
| ^^^^^ second mutable borrow occurs here
119 | step(source, &mut state);
120 | }
| - first borrow ends here
fn step<'a>(source: &'a str,
state: &mut Vec<&'a str>)
fn step<'a, 'x>(source: &'a str,
state: &'x mut Vec<&'a str>)
struct MyStruct<'a: 'x, 'x> {
pub source: &'a str,
pub state: &'x mut Vec<&'a str>,
}
{
let s = MyStruct{source: source, state: state};
func(s);
}