Rustlings function exercise and ownership

Hello everyone!
I am doing Rustlings, such a nice bedtime occupation :smile:.

I have a question about functions4.rs. The error is that sale_price has no return value, but I was certain that it was that is even took ownership of the variable price? Why is it not taking ownership and consuming at line

   num % 2 == 0

:thinking:?

fn main() {
    let original_price = 51;
    println!("Your sale price is {}", sale_price(original_price));
}

fn sale_price(price: i32) {
    if is_even(price) {
        price - 10
    } else {
        price - 3
    }
}

fn is_even(num: i32) -> bool {
    num % 2 == 0
}

The signature of sale_price doesn't have a return type, it should be
fn sale_price(price: i32) -> i32 {

3 Likes

I think you need to declare a return type:

fn sale_price(price: i32) -> i32
2 Likes

Thank you, I saw that :slightly_smiling_face:.
The first thing I thought about was that price was sent as "num" into the even function and should be consummed there.
What I am wondering is why is even does not consume price?

i32 implements the Copy trait, which means it does not get moved/consumed.

2 Likes

Oooooh I see. The plot thickens and I will read about it in the docs. Thank you everyone!

1 Like

The book has a dedicated section on this topic: Stack-Only Data: Copy.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.