Allocate on stack or heap and pass to fn x()

I'm learning Rust.
I wanted to test my theory that I can create array on the stacks, or vecs on the heap, and that I can have a single function process them as slices.

Could an experienced rustacean please confirm if this looks right?

fn print_slice(x: &[i32]) {
    println!("slice: {:?}", x)
}

#[test]
fn pass_immut_heap_or_stack() {
    let stack = [5, 6, 7];
    print_slice(&stack);

    let heap: Vec<i32> = Vec::from([1, 2, 3]);

    print_slice(heap.as_slice());
}

It seems to work, which is super cool!

It's really neat you can store medium-sized arrays on the heap or stack and have them processed by a single function. (I don't think I could do this in C# or Go. Right?)

Thanks for any thoughts or feedback.

Since "stack" or "heap" is not a part of the type of references, where you get your &[T] from doesn't have an effect on their behavior. The only thing that matters is lifetimes, but whether something lives on the stack or on the heap almost never matters in practice. (A notable exception is pinning, but that's a rather advanced and unsafe topic, so you can probably just ignore it for a long while.)

Go performs escape analysis to decide whether things go on the stack or the heap, and "heap" and "stack" isn't part of the type system in Go, either, so you could write a similar function that takes a slice and then it would work either way.

I'm not familiar enough with C# to be able to tell with certainty, but the JIT probably tries to perform the same kind of optimization on arrays.

1 Like

Oh your right about the escape analysis, and where things get placed under Go. But I do really like that I can control this under Rust. :smile:

Yeah, in Rust stuff goes reliably where you put it. With Go and C#, you can never be 100% sure, as it depends on how smart and persistent their respective optimizers are. (Which are improving continuously, but it's still nice to be sure.)

1 Like

C# has stackalloc, but it cannot be assigned to a normal T[].

1 Like

I guess what you are saying here, is that they can't be used as array types, just the Span<_> types?