Languages/RUST

[RUST] TRPL : Chapter3 - Programming

odaebum 2024. 11. 26. 23:35
728x90

섀도잉 or 섀도우

  • 섀도우 : 이전에 존재하던 변수 값을 가려버리는 것.
  • JS 언어에서는 불가능 하지만, RUST에서는 가능하다.

타입

  • 정수형

    image.png

    • 정수 오버플로

      image.png

  • 부동 소수점 유형

    • f32
    • f64
  • 튜플

      let tup: (i32, f64, u8) = (500, 6.4, 1);
      let (x, y, z) = tup;
    
      println!("The value of y is: {y}");
  • 배열

      let a: [i32; 5] = [1, 2, 3, 4, 5];
    
      let a = [3; 5]; //초기화
      let a = [3, 3, 3, 3, 3];

표현식

fn main() {
    let y = {
        let x = 3;
        x + 1
    };

    println!(y);
}

표현식의 마지막 줄에는 세미콜론이 들어가지 않는다.

즉, 반환은 세미콜론이 들어가지 않는다.

세미콜론이 들어가면 → 명령문으로 바뀌어서 값을 반환하지 않는다.

제어 흐름

루프

  1. loop : 명시적으로 중지하라고 말할 때까지 계속해서 실행

    1. 값 반환

       fn main() {
           let mut counter = 0;
      
           let result = loop {
               counter += 1;
      
               if counter == 10 {
                   break counter * 2;
               }
           };
      
           println!("The result is {result}");
       }
    2. 루프 레이블

       fn main() {
           let mut count = 0;
           'counting_up: loop {
               println!("count = {count}");
               let mut remaining = 10;
      
               loop {
                   println!("remaining = {remaining}");
                   if remaining == 9 {
                       break;
                   }
                   if count == 2 {
                       break 'counting_up;
                   }
                   remaining -= 1;
               }
      
               count += 1;
           }
           println!("End count = {count}");
       }
  1. while : 조건 동안 true

  2. for : python의 for과 비슷

    1. 유형 1.

       fn main() {
           let a = [10, 20, 30, 40, 50];
      
           for element in a {
               println!("the value is: {element}");
           }
       }
    2. 유형 2.

       fn main() {
           for number in (1..4).rev() {
               println!("{number}!");
           }
           println!("LIFTOFF!!!");
       }
      
       3!
       2!
       1!
       LIFTOFF!!!
728x90