Not too sure why Rust takes ownership if we do something like this.
fn main()
{
let x:u32 = 10;
let y:u32 = 20;
println!("Value is: {}", cal_rect(x, y));
println!("{}", x); // This is invalid as the cal_rect() function took ownership of x and y
}
fn cal_rect(x:u32, y:u32) -> u32
{
x * y
}
I know that we can use references in the cal_rect() to borrow the reference rather than to take ownership but why can't the cal_rect() function by default just copy the value of x and y instead of taking ownership, like Java does it?
Have you actually tried to run this? Because it does compile and run
Note that u32 implements the Copy trait which gives it copy semantics. Meaning everywhere that it would have moved, it is copied instead. (note that both a move and a copy compile down to the exact same code, and the difference is only in terms of compiler analysis)
Like @RustyYato says, if a type implements Copy trait its values follow copy semantics. Move semantics transfer ownership from caller to the called function, hence we may need to use reference. There is a section in stdlib discussing whether to implement Copy for user types.