Rust

RUST Documentation 따라 공부하기 3

2019.12.30


Common Programming Concepts with RUST

Variables & Mutability

fn main() {
  let x = 1;
  x = 2; // error, because x is immutable
  println!("x : {}", x);
  
    let mut y = 1;
  y = 2;
  println!("y : {}", y);
  
  const MAX_POINTS: u32 = 100_000;
  // const에서는 mut 옵션을 사용할 수 없다.
}

Shadowing

fn main() {
  let x = 1;
  let x = x + 2; // immutable 함이 계속 유지된다. 에러 발생 x
  let x = x * 2;
  
  println!("x : {}", x);
  
  let spaces = "    ";
  let spaces = spaces.len();
  
  
  let mut mutspaces = "   ";
  mutspaces = mutspaces.len(); // error, mutable한 것은 data 형식이 같아야한다.
}

Data types

  • Scalar types

    • Integer types

      i8, i16, i32, i64, i128, isize

      u8, u16, u32, u64, u128, usize

      isize / usize depends on the kind of computer

      Note that all number literals except the byte literal allow a type suffix, such as 57u8, and _ as a visual separator, such as 1_000.

      Integer overflow 발생시, debug mode에서는 panic 발생

      하지만, release 모드에서는 자동으로 그 값을 넘긴다. ex, u8, 256 -> 0, 257 -> 1

    • Floating-point types

      f32, f64 : default

    • Boolean type

      bool

    • Character type

      Note that char literals are specified with single quotes, as opposed to string literals, which use double quotes.

  • Compound types

    • Tuple type

      Tuples have a fixed length: once declared, they cannot grow or shrink in size.

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

      we can access a tuple element directly by using a period (.) followed by the index of the value we want to access.

      fn main() {
          let x: (i32, f64, u8) = (500, 6.4, 1);
          let five_hundred = x.0;
          let six_point_four = x.1;
          let one = x.2;
      }
      
    • Array type

      Unlike a tuple, every element of an array must have the same type. Arrays in Rust are different from arrays in some other languages because arrays in Rust have a fixed length, like tuples.

      fn main() {
          let a = [1, 2, 3, 4, 5];
              let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
            let a: [i32; 5] = [1, 2, 3, 4, 5];
      
            let a = [3; 5];
            // [3,3,3,3,3]
      }
      

Rust protects you against this kind of error by immediately exiting instead of allowing the memory access and continuing.