简体   繁体   English

Rust的for循环中未分配字符串返回值

[英]String return value does not get assigned within for-loop in Rust

Given this code-snippet: 给出以下代码片段:

pub fn verse(start_bottles: i32) -> String {
    let mut song_template: String = "%1 of beer on the wall, %2 of beer.\n%3, %4 of beer on the wall.\n".to_string();

    match start_bottles {
        0 => lyrics_no_bottles(&mut song_template),
        1 => lyrics_one_bottle(&mut song_template),
        2 => lyrics_two_bottles(&mut song_template),
        _ => lyrics_more_bottles(&mut song_template, start_bottles)
    }
    song_template
}

pub fn sing(first: i32, last: i32) -> String {
    let mut song: String = "".to_string();
    for num in (8..6).rev() {
        song = verse(1);
    }
    song
}

As I output verse(1) it works fine - the tested string appears and is complete. 当我输出verse(1)它工作正常-被测试的字符串出现并完成。 But when I assign the result of verse(1) to the String binding song , song seems to be empty? 但是,当我将verse(1)的结果分配给String绑定songsong似乎为空吗? I do not understand this behaviour. 我不了解这种行为。

Because that's not how ranges work; 因为那不是范围的工作方式; it's got nothing to do with the strings. 它与琴弦无关。 If you run the following: 如果运行以下命令:

fn main() {
    for i in 8..6 {
        println!("a: {}", i);
    }
    for i in (8..6).rev() {
        println!("b: {}", i);
    }
    for i in 6..8 {
        println!("c: {}", i);
    }
    for i in (6..8).rev() {
        println!("d: {}", i);
    }
}

You get the following output: 您将获得以下输出:

c: 6
c: 7
d: 7
d: 6

Ranges only count up, they never count down. 范围只会递增,而不会递减。 rev reverses the order of the sequence you give it; rev反转您给它的顺序; it doesn't turn an empty sequence into a non-empty one. 它不会将一个空序列变成一个非空序列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM