在两个独立的向量中创建对Rust字符串的引用

3

我有一个输入的字符串向量,我想创建两个包含引用(&str)的向量,这些引用指向这些字符串。以下是我尝试的简化版本(输入被替换为简单的向量初始化):

let colours = vec!["red".to_string(), "black".to_string(), "blue".to_string()];
let mut starts_with_b = Vec::new();
let mut ends_with_e = Vec::new();

for colour in colours {
    if colour.starts_with("b") {
        starts_with_b.push(&*colour);
    }
    if colour.ends_with("e") {
        ends_with_e.push(&*colour);
    }
}

println!("{:?}", starts_with_b);
println!("{:?}", ends_with_e);

这段代码会产生编译器错误“'colour' does not live long enough”(颜色不够长久)。我该如何解决这个问题?

我发现,如果我使用字符串引用&str开头,就不存在这个问题:

let colours = vec!["red", "black", "blue"];
let mut starts_with_b = Vec::new();
let mut ends_with_e = Vec::new();

for colour in colours {
    if colour.starts_with("b") {
        starts_with_b.push(colour);
    }
    if colour.ends_with("e") {
        ends_with_e.push(colour);
    }
}

println!("{:?}", starts_with_b);
println!("{:?}", ends_with_e);
2个回答

5
你的代码问题出在临时变量colour是一个被移动了的String,这意味着它的生命周期非常短暂。在你的starts_with_bends_with_e向量中,你需要存储对colours中数值的引用。可以通过在迭代过程中 移动colours中的值来轻松实现此操作。最简单的方法是这样做:
for colour in &colours {

改为这样:

for colour in colours {

那样的话,colour 的类型将会是 &String 而不是(已移动的)String,所以你可以直接推送 colour。请注意,那样的话,starts_with_bends_with_e 的类型将是 Vec<&String> 而不是你要求的 Vec<&str>。我想这对你来说不会有问题,但如果有问题的话,你可以通过调用 push(&colour[..]) 而不是 push(colour) 来轻松地让它们成为 Vec<&str>

1
您可以在 colours 的引用上使用 for 循环:
let colours = vec!["red".to_string(), "black".to_string(), "blue".to_string()];
let mut starts_with_b = Vec::new();
let mut ends_with_e = Vec::new();

for colour in &colours {
    if colour.starts_with("b") {
        starts_with_b.push(colour);
    }
    if colour.ends_with("e") {
        ends_with_e.push(colour);
    }
}

println!("{:?}", starts_with_b);
println!("{:?}", ends_with_e);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接