简体   繁体   中英

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. But when I assign the result of verse(1) to the String binding song , song seems to be empty? 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; it doesn't turn an empty sequence into a non-empty one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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