Challenge: Types and Memory Management
Test your understanding of what you learned in this chapter by tackling a stack and heap memory allocation problem.
We'll cover the following
Challenge
In this challenge, we’ll explore how we can store data both on the stack and on the heap. This challenge is designed to assess your understanding of memory management, ownership, and lifetimes in Rust. You’re required to create a program that involves both stack-allocated and heap-allocated data, emphasizing the importance of choosing the appropriate memory allocation strategy for different scenarios.
Task
Create a program that calculates the sum of squares for a given list of numbers. However, to make things interesting, part of the list will be stored on the stack, and the other part will be stored on the heap. Given below are some instructions you’re supposed to follow:
Create a stack-allocated array named
stack_numbers
containing at least three integers of your choice.Create a heap-allocated vector named
heap_numbers
containing at least three integers of your choice. Use theVec
type for dynamic allocation.Implement a function named
sum_of_squares
that takes a reference to a slice of integers and calculates the sum of squares for the elements.Call the
sum_of_squares
function twice:Once with a slice referencing the stack-allocated array.
Once with a slice referencing the heap-allocated vector.
Print the sum of squares for both the stack-allocated and heap-allocated data.
Try it yourself
Implement the given instructions in the code block below:
Get hands-on with 1400+ tech skills courses.