0

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.

3
  • 1
    Just a comment about your code, unrelated to the question: you can remove those explicit String type annotations, when your right-hand-side already is a string (which it is in case of using to_string()). Commented Jun 24, 2016 at 7:14
  • I keep it for readability...I dont like inference much in every case...want to see the type at all times Commented Jun 24, 2016 at 8:21
  • 1
    I can completely understand that, but it is pretty important to settle on one coding style within the community such that everyone can quickly read everyone else's code, even if it feels wrong for newcomers of a language. But this is nothing to settle in the SO comment section :) Commented Jun 24, 2016 at 11:15

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.