Search code examples
functionrustreturnreturn-value

Why is my function not returning the expected result?


My function is not returning the expected result. It's giving 0 instead of 2, that is the result of 1 + 1. Why is this happening and what could I do to fix it? Here is the code:

// Calculate the weight of a building

fn main() {
    let weight = sum(1, 1); //calling sum(1,1) and trying to bind its result to a variable
    println!("The result is {}.", weight); //printing "weight"
}

//function to perform "beams + columns" and use it in main()
fn sum(beams: u32, columns: u32) -> u32 {
    let beams: u32 = 0; 
    let columns: u32 = 0;

    beams + columns //Trying to return the result
}

Solution

  • You have created two variables that initalized to 0 in function sum, hence the result being 0.

    You should delete these two variables in order to get the correct result.