Printing Return Values When Using -> Operator


#1

Is there an easy way to print a return value when using ->? Only one value in the function ‘add_one’ should be returned, and the code works if I remove the assignment to z. But what is I want to do something with the returned value in the function. Something like Perl’s $_.

fn main() {

printsomething();
print_number (9);
add_one(6);

}


fn printsomething() {

println!("hello");

}

fn print_number(x: i32) {
    println!("x is: {}", x);
}

fn add_one(x: i32) -> i32 {   //compiler doesn't like this
    let z = x + 1
    println!("added value: {}", z);  
}

Here is the compiler error:

D:\rust\bin>rustc simple.rs
simple.rs:22:5: 22:12 error: expected one of ., ;, or an operator, found pr intln
simple.rs:22 println!(“added value: {}”, z);
^~~~~~~
error: aborting due to previous error

I understand the need for a return value:

D:\rust\bin>rustc --explain E0269
Functions must eventually return a value of their return type. For example, in
the following function

fn foo(x: u8) -> u8 {
    if x > 0 {
        x // alternatively, `return x`
    }
    // nothing here
}

If the condition is true, the value x is returned, but if the condition is
false, control exits the if block and reaches a place where nothing is being
returned. All possible control paths must eventually return a u8, which is not

happening here.

An easy fix for this in a complicated function is to specify a default return
value, if possible:

fn foo(x: u8) -> u8 {
    if x > 0 {
        x // alternatively, `return x`
    }
    // lots of other if branches
    0 // return 0 if all else fails
}

It is advisable to find out what the unhandled cases are and check for them,
returning an appropriate value or panicking if necessary.


#2

I think the easiest way to do this is:

fn add_one(x: i32) -> i32 {
    let z = x + 1;  // The semicolon here finishes the statement.
    println!("added value: {}", z);  
    z
}

Whereas your function foo could look something like:

fn foo(x: u8) -> u8 {
    if x > 0 {
        x
    } else {
        0
    }
}

#3

Rust has no concept of “a function returns the value of the last statement that evaluated to a value” as in Perl 5. In Rust, all statements evaluate to a value, more like Lisp or ML, so I don’t understand what you’re trying to get at with foo in the second half of your message.

For add_one specifically, I endorse @troiganto’s solution.