์Šฌ๋ผ์ด์Šค

์Šฌ๋ผ์ด์Šค๋Š” ํฐ ์ปฌ๋ž™์…˜์˜ ์ผ๋ถ€(ํ˜น์€ ์ „์ฒด)๋ฅผ ๋ณด์—ฌ์ฃผ๋Š” ๋ทฐ(view)์ž…๋‹ˆ๋‹ค:

fn main() {
    let mut a: [i32; 6] = [10, 20, 30, 40, 50, 60];
    println!("a: {a:?}");

    let s: &[i32] = &a[2..4];

    println!("s: {s:?}");
}
  • ์Šฌ๋ผ์ด์Šค๋Š” ๋‹ค๋ฅธ(์Šฌ๋ผ์ด์Šค ๋œ) ํƒ€์ž…์œผ๋กœ๋ถ€ํ„ฐ ๋ฐ์ดํ„ฐ๋ฅผ โ€™๋นŒ๋ คโ€™์˜ต๋‹ˆ๋‹ค.
  • ์งˆ๋ฌธ: s๋ฅผ ์ถœ๋ ฅํ•˜๊ธฐ ์ „์— a[3]์„ ์ˆ˜์ •ํ•˜๋ฉด ๋ฌด์Šจ ์ผ์ด ์žˆ์–ด๋‚ ๊นŒ์š”?
This slide should take about 10 minutes.
  • ์Šฌ๋ผ์ด์Šค๋Š” ์šฐ์„  a๋ฅผ ๋นŒ๋ฆฐ๋‹ค์Œ, ์‹œ์ž‘๊ณผ ๋ ์ธ๋ฑ์Šค๋ฅผ ๋ธŒ๋ž˜ํ‚ท([])์•ˆ์— ์ง€์ •ํ•ด์„œ ๋งŒ๋“ญ๋‹ˆ๋‹ค.

  • ์Šฌ๋ผ์ด์Šค๊ฐ€ ์ธ๋ฑ์Šค 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•œ๋‹ค๋ฉด ์‹œ์ž‘ ์ธ๋ฑ์Šค๋Š” ์ƒ๋žต ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค. ์ฆ‰ &a[0..a.len()]์™€ &a[..a.len()] ๋Š” ๋™์ผํ•ฉ๋‹ˆ๋‹ค.

  • ๋งˆ์ง€๋ง‰ ์ธ๋ฑ์Šค๋„ ์ƒ๋žต ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ &a[2..a.len()] ์™€ &a[2..]๋Š” ๋™์ผํ•ฉ๋‹ˆ๋‹ค.

  • ๋”ฐ๋ผ์„œ ์ „์ฒด ๋ฐฐ์—ด์— ๋Œ€ํ•œ ์Šฌ๋ผ์ด์Šค๋Š” &a[..]๊ฐ€ ๋ฉ๋‹ˆ๋‹ค.

  • s๋Š” i32๋“ค๋กœ ์ด๋ฃจ์–ด์ง„ ์Šฌ๋ผ์ด์Šค์— ๋Œ€ํ•œ ์ฐธ์กฐ์ž…๋‹ˆ๋‹ค. s์˜ ํƒ€์ž…(&[i32])์— ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๊ฐ€ ๋น ์ ธ์žˆ์Œ์— ์ฃผ๋ชฉํ•˜์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค. ์ฆ‰, ์Šฌ๋ผ์ด์Šค๋ฅผ ์ด์šฉํ•˜๋ฉด ๋‹ค์–‘ํ•œ ๊ธธ์ด์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๋‹ค๋ฃฐ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

  • Slices always borrow from another object. In this example, a has to remain โ€˜aliveโ€™ (in scope) for at least as long as our slice.

  • The question about modifying a[3] can spark an interesting discussion, but the answer is that for memory safety reasons you cannot do it through a at this point in the execution, but you can read the data from both a and s safely. It works before you created the slice, and again after the println, when the slice is no longer used.