Update for newer Rust versions: The below code contains deprecated (and removed) constructs. Replace box x
with Box::new(x)
.
I'm playing around with the most basic concepts of Rust and have a follow up question to my previous question: Why does the binary + operator not work with two &mut int?
I want to create an int
on the heap and I want to pass it to another function for modification.
I came up with this:
fn increment(number: &mut Box<int>) {
**number = **number + **number;
println!("{}", number);
}
fn main() {
let mut test = box 5;
increment(&mut test);
println!("{}", test);
}
This prints
10
10
which is what I want.
However, the **
looks odd and I figured I could also write this kind of thing:
fn increment(number: &mut int) {
*number = *number + *number;
println!("{}", number);
}
fn main() {
let mut test = box 5;
increment(&mut* test);
println!("{}", test);
}
In respect to my intention to create an int
on the heap and modify it in another function, which of this methods is correct (if any)? To me it looks as if in the second example, the variable is moved from the heap back to the stack before it is passed to the increment
method which is not what I want. On the other hand the **
syntax of the first example looks pretty odd. :-/
You're just about there. From the Rust tutorial:
In the case of
owned_box
, however, no explicit action is necessary. The compiler will automatically convert a boxbox point
to a reference like&point
. This is another form of borrowing; in this case, the contents of the owned box are being lent out.
So all you need to do is take advantage of the implicit borrowing:
fn increment(number: &mut int) {
*number = *number + *number;
}
fn main() {
let mut test = box 5;
increment(test);
println!("{}", test);
}
I don't think the value of test
is moved back to stack here. I suspect that a conversion from Box
to a borrowed reference won't have any run time overhead, but I don't know enough about the implementation to be certain.