Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Activity 23: Draw the slice

Name:

Both problems are done during lecture. Hand this in on your way out.

Stack on the left, heap on the right. Label everything!

Problem 1

#![allow(unused)]
fn main() {
let data = vec![5, 10, 15, 20, 25];
let slice = &data[1..4];
}













How many fields does data have on the stack? How many does slice?



Problem 2

fn analyze(numbers: &Vec<i32>, window: &[i32]) -> i32 {
    let first = window[0];
    let sum_ref = &first;

    // DRAW HERE

    let total = first + numbers.len() as i32;
    total
}

fn main() {
    let data = vec![100, 200, 300, 400];
    let slice = &data[1..3];

    let result = analyze(&data, slice);
}





























sum_ref is a reference. Is anything it touches on the heap?



Solutions

Problem 1. data is a ptr/len/cap handle on the stack, heap buffer holding 5, 10, 15, 20, 25. slice is two words on the stack: a pointer to the element at index 1, and the length 3.

Stack:                            Heap:
┌───────────────────────┐
│ main()                │
│ ├ data: Vec<i32>      │        ┌────┬────┬────┬────┬────┐
│ │  ├ ptr ─────────────┼───────▶│ 5  │ 10 │ 15 │ 20 │ 25 │
│ │  ├ len: 5           │        └────┴────┴────┴────┴────┘
│ │  └ cap: 5           │               ▲
│ └ slice: &[i32]       │               │ (at the 10, index 1)
│    ├ ptr ─────────────┼───────────────┘
│    └ len: 3           │
└───────────────────────┘

Problem 2. Two frames. main has data (handle, heap buffer 100, 200, 300, 400), slice (ptr to index 1, len 2), and result, which is ??? because analyze hasn't returned. analyze has numbers, an arrow back to main's handle; window, a copy of the two-word slice; first, an i32 holding 200 on analyze's frame; sum_ref, an arrow to first, which is on the stack; and total, ??? because that line hasn't run yet.

Stack:                              Heap:
┌─────────────────────────┐
│ analyze()               │
│ ├ numbers: &Vec<i32> ───┼─────┐
│ ├ window: &[i32]        │     │
│ │  ├ ptr ───────────────┼─────┼───────────┐
│ │  └ len: 2             │     │           │
│ ├ first: i32 = 200      │◀─┐  │           │
│ ├ sum_ref: &i32 ────────┼──┘  │           │
│ └ total: i32 = ???      │     │           │
├─────────────────────────┤     │           │
│ main()                  │     │           ▼ (window: at the 200, index 1)
│ ├ data: Vec<i32>        │◀────┘  ┌─────┬─────┬─────┬─────┐
│ │  ├ ptr ───────────────┼───────▶│ 100 │ 200 │ 300 │ 400 │
│ │  ├ len: 4             │        └─────┴─────┴─────┴─────┘
│ │  └ cap: 4             │                 ▲
│ ├ slice: &[i32]         │                 │ (slice: the same 200)
│ │  ├ ptr ───────────────┼─────────────────┘
│ │  └ len: 2             │
│ └ result: i32 = ???     │
└─────────────────────────┘