Passing values through functions

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

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ea9027fff67c7ef8294db2243588a6de

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)

2 Likes

I thought it didn’t compile I remember reading it from somehwere? Or did they do an update to their compiler.

I thought I read somehwere that you have to use reference when refering to a variable when passing it through a function?

Like @KrishnaSannasi 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.

1 Like