Is memory allocated when returning a struct?

In the Rust Book, in the following example, is the returned struct allocated on the heap?

If it is, is it always true to assume for a returned non-scalar value that memory is allocated?

If it is not, is it always true that memory is never allocated?

impl Rectangle {
    fn square(size: u32) -> Rectangle {
        Rectangle { width: size, height: size }

That will be on the stack.

Memory allocation in Rust is always explicit at the language level, but you might be abstracted from that detail in more complicated types. For example, a local Vec<T> is a simple structure on the stack with a pointer, length, and capacity, but that pointer refers to a heap allocation.

1 Like