Show return value, not just println in documentation


#1

I have been trying to learn rust and the hardest thing about rust is the return value. In ALL the documentation every example uses println!() and returns nothing. When documenting something,. it would be great if moy only the usage is shown, but it also has a return value, here is an example of how not to do it.

In https://rustbyexample.com/flow_control/match.html, there is this example. It shows how match is used, but it returns nothing. What is I want to use the result of the match later in the scope?

I have used both GO rust and a dozen other languages. I like Rust the best but it is harder to learn than Lisp because the example documentation shows on half the concept.

    match number {
        // Match a single value
        1 => println!("One!"),
        // Match several values
         2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
        // Match an inclusive range
        13...19 => println!("A teen"),
        // Handle the rest of cases
        _ => println!("Ain't special"),
     }

#2

There’s another match example just below in the code that returns a value…

let boolean = true;
// Match is an expression too
let binary = match boolean {
    // The arms of a match must cover all the possible values
    false => 0,
    true => 1,
    // TODO ^ Try commenting out one of these arms
};

#3

Please file bugs for each spot that you find! Rust by Example’s repo is here: https://github.com/rust-lang/rust-by-example

What, in general, is hard when an example doesn’t show a return value? What is it that you’re not sure how to do?


#4

Thanks
The “let = match” syntax was the where I was getting confused, That is the syntax the style I was asking about, so this syntax should work? I was trying to return a struct for an Option<>

I think I found a better way. I use unwrap_or() function instead of a “let = match” statement.
let attrs = HashMap::New
let t = &state.ttype.clone();
let ttype = attrs.get(“type”).unwrap_or(t);

memory:
allocates the “t” in memory,
if the key exist then the memory allocation of t is wasted.

Is there a way to get around this?


#5

Yes, there is .unwrap_or_else which takes a closure that’s only evaluated in the None case.

However, in this case I’m not clear why you need to clone() the state.ttype in the first place.