이 글 공유하기

이메일FacebookRedditWhatsApp

rust 기초 정리

#rust#dev
목차 · 5개 항목

변수

Rust는 기본적으로 변수가 바뀌지 않는다. (immutable)

바꾸려면 let mut 으로 선언해야 한다.

let mut count = 3;
count = 4;

그치만 Rust 도 const 로 변수 선언하는 경우도 있다.

바뀌면 안 되는 설정값, 크기, 제한값 같은 것들은 const로 선언한다.

// 컴파일 타임 상수
const COUNT: u64 = 3;

타입

  • bool = true/false
  • u64 = 음수 없는 큰 정수
  • i64 = 음수 가능한 정수
  • f64 = 실수
  • &str = 고정된 문자열 조각
  • string = 수정 가능한 문자열
let num: u64 = 1_000_000_000;
let fnum: f64 = 12.5;

let fixed: &str = "solana";

let mut name: String = String::from("solana");
name.push_str(" chain"); // solana chain

타입도 한번 정해지면 바뀌지 않는다.

다만 let 을 새로 쓰면 같은 이름으로 다시 만들 수 있다. (shadowing)

let amount = "42";  // 문자열
let amount: u64 = amount.parse().unwrap(); // u64

함수

fn add(a: u64, b: u64) -> u64 {
  a + b
}

fn is_adult(age: u8) -> bool {
  return age >= 18;
}

// 반환값이 없으면 '->' 을 안해줘도 된다.
fn log_message() {
  println!("done")
}

// 마지막 표현식에 `;`이 붙으면 값을 반환하지 않는다.
fn set_count(count: &mut u64) {
  *count = 10;
}

struct

struct User {
  name: String,
  age: u8,
}

let user = User {
  name: String::from("Alice"),
  age: 20,
}

println("{}", user.name)
println("{}", user.age)

impl

struct Counter {
  count: u64,
}

// struct에 함수/메서드를 붙이기
// struct와 impl 이름이 같아야 한다.
impl Counter {
  fn new() -> Self {
    Self {count: 0}
  }

  fn increment(&mut self) {
    self.count += 1;
  }

  fn get_count(&self) -> u64 {
    self.count
  }
}

fn main() {
  let mut counter = Counter::new();

  counter.increment();

  println!("{}", counter.get_counter());
}
  • impl = struct에 함수/메서드를 붙이는 역할
  • &self = 읽기
  • &mut self = 수정
  • self = 소유권 가져감
  • Self = 현재 타입
  • new() = 관습적인 생성자 이름
  • Counter::new() = 타입에 붙은 함수 호출
  • counter.increment() = 값에 붙은 메서드 호출
순서챕터
6Option
7Result<T,E>
8match
9enum
10reference &, &mut
11ownership / move
12borring rule
13lifetime
14module / pub
15trait
16derive / attribute
17macro
18Anchorr
19Solana