Vec

Vec ๋Š” ํž™์— ํ• ๋‹น๋œ ํ‘œ์ค€ ๊ฐ€๋ณ€ ํฌ๊ธฐ ๋ฒ„ํผ์ž…๋‹ˆ๋‹ค:

fn main() {
    let mut v1 = Vec::new();
    v1.push(42);
    println!("v1: len = {}, ์šฉ๋Ÿ‰ = {}", v1.len(), v1.capacity());

    let mut v2 = Vec::with_capacity(v1.len() + 1);
    v2.extend(v1.iter());
    v2.push(9999);
    println!("v2: len = {}, ์šฉ๋Ÿ‰ = {}", v2.len(), v2.capacity());

    // ์š”์†Œ๊ฐ€ ์žˆ๋Š” ๋ฒกํ„ฐ๋ฅผ ์ดˆ๊ธฐํ™”ํ•˜๋Š” ํ‘œ์ค€ ๋งคํฌ๋กœ์ž…๋‹ˆ๋‹ค.
    let mut v3 = vec![0, 0, 1, 2, 3, 4];

    // ์ง์ˆ˜ ์š”์†Œ๋งŒ ์œ ์ง€ํ•ฉ๋‹ˆ๋‹ค.
    v3.retain(|x| x % 2 == 0);
    println!("{v3:?}");

    // ์—ฐ์† ์ค‘๋ณต ์‚ญ์ œ
    v3.dedup();
    println!("{v3:?}");
}

Vec์€ Deref<Target = [T]>๋ฅผ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค. ์ด๋Š” Vec์—์„œ ์Šฌ๋ผ์ด์Šค ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœ ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์˜๋ฏธ์ž…๋‹ˆ๋‹ค.

This slide should take about 10 minutes.
  • Vec is a type of collection, along with String and HashMap. The data it contains is stored on the heap. This means the amount of data doesnโ€™t need to be known at compile time. It can grow or shrink at runtime.
  • Vec<T>๋Š” ์ œ๋„ค๋ฆญ ํƒ€์ž…์ด๊ธฐ๋„ ํ•ฉ๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ T๋ฅผ ๊ผญ ์ง€์ •ํ•ด์ค„ ํ•„์š”๋Š” ์—†์Šต๋‹ˆ๋‹ค. ์ด ๊ฒฝ์šฐ, ๋Ÿฌ์ŠคํŠธ ํƒ€์ž… ์ถ”๋ก ์ด ๋ฒกํ„ฐ์— ์ฒ˜์Œ pushํ•˜๋Š” ๋ฐ์ดํ„ฐ๋กœ T๋ฅผ ์•Œ ์ˆ˜ ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค.
  • vec![...]๋Š” Vec::new() ๋Œ€์‹  ์“ธ ์ˆ˜ ์žˆ๋Š” ํ‘œ์ค€ ๋งคํฌ๋กœ๋กœ์„œ, ์ดˆ๊ธฐ ๋ฐ์ดํ„ฐ๋ฅผ ์ถ”๊ฐ€ํ•œ ๋ฒกํ„ฐ๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  • ๋ฒกํ„ฐ๋Š” [ ]๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ธ๋ฑ์Šค๋กœ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜๋ฉด ํŒจ๋‹‰์ด ๋ฐœ์ƒํ•ฉ๋‹ˆ๋‹ค. ๋Œ€์‹  get์„ ์‚ฌ์šฉํ•˜๋ฉด Option์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. pop ํ•จ์ˆ˜๋Š” ๋งˆ์ง€๋ง‰ ์š”์†Œ๋ฅผ ์ œ๊ฑฐํ•ฉ๋‹ˆ๋‹ค.
  • Slices are covered on day 3. For now, students only need to know that a value of type Vec gives access to all of the documented slice methods, too.