如何返回使用for循环创建的Vector?

时间:2015-04-25 19:32:37

标签: rust

我想用for循环创建一些数据。我用以下来做到这一点。

struct Message<'a> {
    msg: &'a str
}

fn loop_function<'a>() -> Vec<Message<'a>> {
    let mut result = vec![];
    for x in 0..10 {
        result.push(Message { msg: format!("{}", x).trim() });
    }
    result
}

fn main() {
    loop_function();
}

但是当我尝试编译时,我得到跟随x的生命周期的错误。

src/main.rs:8:33: 8:49 error: borrowed value does not live long enough
src/main.rs:8       result.push(Message { msg: format!("{}", x).trim() });
                                               ^~~~~~~~~~~~~~~~
src/main.rs:5:44: 11:2 note: reference must be valid for the lifetime 'a as defined on the block at 5:43...
src/main.rs:5 fn loop_function<'a>() -> Vec<Message<'a>> {
src/main.rs:6     let mut result = vec![];
src/main.rs:7     for x in 0..10 {
src/main.rs:8       result.push(Message { msg: format!("{}", x).trim() });
src/main.rs:9   }
src/main.rs:10     result
               ...
src/main.rs:8:6: 8:60 note: ...but borrowed value is only valid for the statement at 8:5
src/main.rs:8       result.push(Message { msg: format!("{}", x).trim() });
                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/main.rs:8:6: 8:60 help: consider using a `let` binding to increase its lifetime
src/main.rs:8       result.push(Message { msg: format!("{}", x).trim() });
                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error

有没有办法延长生命周期x,以便我可以返回向量?

1 个答案:

答案 0 :(得分:0)

asked the same question recently。它无法完成。链接中的答案有一个很好的解释。我的解决方案是返回String

struct Message {
    msg: String
}

fn loop_function() -> Vec<Message> {
    let mut result = vec![];
    for x in 0..10 {
        result.push(Message { msg: format!("{}", x).trim().to_string() });
    }
    result
}

fn main() {
    loop_function();
}