Post

Rust Structs, Traits and Impl

Rust Structs, Traits and Impl

Rust는 OOP의 특성인 Class 키워드가 없다. 대신에 struct와 impl이 있으므로 이를 혼합하여 사용한다.

다음 예제는 Rust에서 구조적 프로그래밍을 위한 struct, trait, impl 키워드를 살펴볼 것이며 mod 키워드를 통해 다른 rust 파일을 불러와 재사용할 수 있는 모듈(module) 시스템 설명도 포함하였다.

참고로 실행 파일을 static build로 만드는 환경설정은 아래와 같다.

random_info.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
pub struct RandomInfo {
    pub call_count: i64,
    pub some_bool: bool,
    pub some_int: i64,
}

pub trait SomeTrait {
    fn is_vaild(&self) -> bool;
}

impl SomeTrait for RandomInfo {
    fn is_vaild(&self) -> bool {
        self.some_bool
    }
}

impl RandomInfo {
    pub fn new(param_a: bool) -> Self {
        Self {
            call_count: 0,
            some_bool: !param_a,
            some_int: 8,
        }
    }

    pub fn is_smaller(&mut self, compare_to: i64) -> bool {
        self.call_count += 1;
        self.some_int < compare_to
    }
}
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
mod random_info;

use random_info::*;

struct DougsData {
    some_float: f64,
    random: RandomInfo,
}

fn main() {
    let mut dougs_var = DougsData {
        some_float: 10.3,
        random: RandomInfo::new(true),
    };

    let is_this_smaller = dougs_var.random.is_smaller(9);
    let this_some_int = dougs_var.random.call_count;
    println!("{} {}", is_this_smaller, this_some_int);

    let is_vaild = dougs_var.random.is_vaild();
    println!("{}", is_vaild);

    println!("{} {} {}", dougs_var.some_float, dougs_var.random.some_bool, dougs_var.random.some_int);
}
cargo static build

프로젝트 폴더의 Root에 .cargo폴더를 만들고 이 안에 config파일을 만든다.

1
2
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
Rust Naming conventions
ItemConvention
Cratessnake_case (but prefer single word)
Modulessnake_case
TypesCamelCase
TraitsCamelCase
Enum variantsCamelCase
Functionssnake_case
Methodssnake_case
General constructorsnew or with_more_details
Conversion constructorsfrom_some_other_type
Local variablessnake_case
Static variablesSCREAMING_SNAKE_CASE
Constant variablesSCREAMING_SNAKE_CASE
Type parametersconcise CamelCase, usually single uppercase letter: T
Lifetimesshort, lowercase: ‘a
Reference
This post is licensed under CC BY 4.0 by the author.