Skip to content
The Chat Archive
Human-written demonstration (OpenAssistant volunteers)· OpenAssistant (human-written) OpenAssistant Conversations (oasst2)

I've been learning Rust for a few weeks now, and have been trying my hand at the…

In OpenAssistant data, “assistant” turns were written by human volunteers as demonstrations. They are not model outputs.
  1. User

    I've been learning Rust for a few weeks now, and have been trying my hand at the fizzbuzz problem.

    Code: fn fizzbuzz<'a>(n: usize) -> &'a str { match (n % 3, n % 5) { (0, 0) => "fizzbuzz", (0, ) => "fizz", (, 0) => "buzz", _ => n.to_string().as_str(), } }

    For some reason, I get a compiler error that I'm struggling to understand.

    Error: error[E0515]: cannot return value referencing temporary value --> src\main.rs:36:2 | 36 | / match (n % 3, n % 5) { 37 | | (0, 0) => "fizzbuzz", 38 | | (0, ) => "fizz", 39 | | (, 0) => "buzz", 40 | | _ => n.to_string().as_str(), | | ------------- temporary value created here 41 | | } | |_____^ returns a value referencing data owned by the current function

    For more information about this error, try rustc --explain E0515.

    Could you please explain to my why this happens and how I can fix it?

  2. Assistant

    It's trying to return a reference to str, which is a stack allocated object, your options are to Box it, or used a Boxed type like string, or deal with lifetimes (which people tend to avoid at every step).

    The simplest way to solve this is to just return a String rather than a & str:

    fn fizzbuzz(n: usize) -> String { match (n % 3, n % 5) { (0, 0) => "fizzbuzz".to_string(), (0, ) => "fizz".to_string(), (, 0) => "buzz".to_string(), _ => n.to_string() } }

  3. User

    Thank you, can you simulate the expected output?

  4. Assistant

    Sure.

    To get some output, however, you would need to call the function, e.g.

    fn main() {
        // Print the first 20 fizzbuzz results
        for i in 1..21 {
            println!("i={}, result={}", i, fizzbuzz(i));
        }
    }
    

    The above would output something like this:

    i=1, result=1
    i=2, result=2
    i=3, result=fizz
    i=4, result=4
    i=5, result=buzz
    i=6, result=fizz
    i=7, result=7
    i=8, result=8
    i=9, result=fizz
    i=10, result=buzz
    i=11, result=11
    i=12, result=fizz
    i=13, result=13
    i=14, result=14
    i=15, result=fizzbuzz
    i=16, result=16
    i=17, result=17
    i=18, result=fizz
    i=19, result=19
    i=20, result=buzz
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.