본문 바로가기
Rust

[Rust] Vector 예제 (16일차)

by 꾸압 2022. 12. 27.

 

<예제 코드_1>

// main.rs
fn main() {
    // Create an empty vector
    let mut v: Vec<i32> = Vec::new();

    // Push some elements onto the vector
    v.push(1);
    v.push(2);
    v.push(3);

    // Access elements of the vector using indexing
    let third: &i32 = &v[2];
    println!("The third element is {}", third);

    // Iterate over the elements of the vector
    for i in &v {
        println!("{}", i);
    }
}

 


 

<예제 코드_2>

use std::vec::Vec;

fn main() {
    // Create a new, empty vector
    let mut v: Vec<i32> = Vec::new();

    // Push some values onto the vector
    v.push(1);
    v.push(2);
    v.push(3);

    // Iterate over the values in the vector
    for i in &v {
        println!("{}", i);
    }

    // Get a reference to the value at index 1
    let second: &i32 = &v[1];
    println!("The second value is {}", second);

    // get a mutable reference to the value at index 0
    let first: &mut i32 = &mut v[0];
    *first = 42;
    println!("The first value is now {}", first);

    // Drop the vector and free its memory
    drop(v);
}

// Vector는 Dinamically sized array로 크기가 자유롭게 커지고 줄어듦
// Dynamically-allocated buffer 근처에 Wrapper로서 기능

 


 

<예제 코드_3>

fn main() {
    // Create a new, empty vectorsh
    let mut v: Vec<i32> = Vec::new();

    // Push elements onto the vector
    v.push(1);
    v.push(2);
    v.push(3);

    // Access elements of the vector by index
    println!("the third element of v is {}", v[2]);

    // Iterate over the elemelnts of the vector
    for i in &v {
        println!("{}", i);
    }

    // Modify elements of the vector
    for i in &mut v {
        *i += 1;
        println!("Changed Value : {}", i);
    }

    // Get the length of the vector
    println!("The length of v is {}", v.len());

    drop(v);
}

 


 

<참조> https://chat.openai.com/chat/

 

 

댓글