์ฌ๋ผ์ด์ค
์ฌ๋ผ์ด์ค๋ ํฐ ์ปฌ๋์ ์ ์ผ๋ถ(ํน์ ์ ์ฒด)๋ฅผ ๋ณด์ฌ์ฃผ๋ ๋ทฐ(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]
์ ์์ ํ๋ฉด ๋ฌด์จ ์ผ์ด ์์ด๋ ๊น์?
-
์ฌ๋ผ์ด์ค๋ ์ฐ์
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 througha
at this point in the execution, but you can read the data from botha
ands
safely. It works before you created the slice, and again after theprintln
, when the slice is no longer used.