3 ms·
I'm still pretty unexperienced with the language so take this with a grain of salt, but I think one of the reasons people allocate on the heap is because it is
by saosebastiao 13y ago
I'm still pretty unexperienced with the language so take this with a grain of salt, but I think one of the reasons people allocate on the heap is because it is so tempting to write functions that accept borrowed pointers as arguments, due to the flexibility of taking either borrowed or managed pointers. However, when you want to call the same function using a stack variable, you have to change your call invocation or the function, which is just an extra pain whenever you want to refactor.
For example:
fn foo(a: &int){
a.do_something()
}
fn main(){
let a = @5;
let b = ~5;
let c = 5;
foo(a);
foo(b);
foo(c); // ack!
//laboriously hunt down all my invocations
foo(&c); //much better
}
- kibwen 13y agoFirst I just want to point out that you're not allocating on the heap just by using references. This: let x = &1; ...is just sugar for: let x1 = 1; // allocated on the stack let x = &x1; // reference to a stack allocation Currently you only allocate on the heap when you use either ~ or @ pointers. And if you're writing an API for widespread consumption, then writing functions that take arguments by reference is actually encouraged since it gives the caller the maximum amount of flexibility. As for the pain of refactoring your code to move from heap-allocations to stack-allocations, this is exactly why we're so fervent to encourage people to use stack-allocated values from the get-go. :) We're fans of Python's philosophy of making things explicit, which explains why we're different from C++ in this particular detail (i.e. we make you explicitly acknowledge when you're passing a reference to a function that expects a reference).