logo MSJO.kr

Rust-002, 프로젝트 디렉터리 구조

2023-03-07
MsJ

Rust 프로젝트는 터미널에서 cargo 명령어를 통해서 생성 할 수 있다. 프로젝트 hello를 생성한다고 가정할 때 임의의 디렉터리에서 cargo new hello --bin을 실행하면 hello 디렉터리가 만들어지고 이 안에 기본 뼈대가 생성된다. 또는 직접 hello 디렉터리를 만들고 이 안에서 cargo init 명령어를 실행해도 똑같은 결과를 볼 수 있다.

기본 프로젝트 구조
hello\
    src\
        main.rs
    Cargo.toml
  • main.rs : main() 함수가 존재하는 기본 메인 파일
  • Cargo.toml : 프로젝트 정보 및 외부 모듈 등록을 위한 [dependencies]

hello 디렉터리 안에서 cargo check, cargo build, cargo run을 실행하면 결과를 볼 수 있는데 check은 문법 확인, build는 결과 생성, run은 결과를 실행한다. 바로 실행하고 싶다면 cargo run을 실행한다.

프로젝트 모듈 확장

실제로 개발할 때 소스 파일을 모듈(라이브러리)별로 구분하여 진행하게 되는데 간단한 함수를 추가하여 모듈별로 나누는 예시를 살펴보자.1 helpers는 임의로 지정한 이름이다.

hello\
    .cargo\
        config
    src\
        helpers\
            mod_number.rs
            mod_string.rs
        helpers.rs
        main.rs
    Cargo.toml
    rustfmt.toml
  • config : 컴파일 옵션 작성 : .cargo 디렉터리 안에 작성
  • helpers 디렉터리 : 모듈을 이 안에 저장
  • helpers.rs : helpers 디렉터리 안의 모듈 파일을 연결
  • rustfmt.toml : Rust 코드 형식을 지정한다. 소스 포맷, style guidelines.2
config : static 빌드 옵션
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
rustfmt.toml
max_width = 200
fn_args_layout = "Compressed"
use_small_heuristics = "Max"
mod_number.rs
pub fn add_number(a:i32, b:i32) -> i32 {
    a + b
}
mod_string.rs
pub fn function() {
    println!("{}", "mod_string::function()")
}
helpers.rs
// pub으로 선언하면 main에서 helpers 직접 접근 가능
mod mod_number;
mod mod_string;

pub fn function_string() {
    mod_string::function();
}

pub fn function_number() {
    let result = mod_number::add_number(2, 3);
    println!("mod_number::add_number() : {}", result);
}
main.rs
mod helpers;

fn main() {
    println!("Hello, world!");
    helpers::function_string();
    helpers::function_number();
}

/* 결과
Hello, world!
mod_string::function()
mod_number::add_number() : 5
*/

Rust 모듈, 추천 강좌 : RustCast, “ Rust module system explained”

Reference
  1. doc.rust-lang.org, “File hierarchy”
  2. rust-lang.github.io, “Configuring Rustfmt, Options”

Prεv(Θld)   Nεxt(Nεw)
Content
Search     RSS Feed     BY-NC-ND