ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • rust 시작하기
    프로그래밍 기초/Rust 2022. 2. 19. 21:05
    반응형

    개발 환경

    이 문서에서 진행한 필자의 개발 환경은 다음과 같다.

    • desktop: macbook pro 13 2020
    • cpu: Intel Core i7 4core
    • memory: 32GB

    각 명령어는 MacOS, Linux 등의 OS는 잘 동작하겠지만 Windows는 동작하지 않을 수도 있다. 그 때는 "참고"절의 문서들을 참고하라.

    rustup 및 cargo 설치

    rustup이란 rust 버전 및 관련 도구들을 위한 커맨드라인 도구이다. rustc, rustfmt, cargo 등이 있다.

     

    rustc는 프로그래밍 경험이 있다면 gcc 등의 컴파일러라고 이해하면 편하다. 없다면, 내가 만든 rust 코드를 컴퓨터가 이해할 수 있는 언어로 변경해주는 도구라고 생각하자.

     

    rustfmt는 내가 작성한 코드를 포맷팅해주는 도구라고 보면 된다. 각 회사마다, 프로젝트마다 코드를 작성하는 규칙이 있는데 이 도구를 사용하면, 대중적인 규칙으로 코드를 다시 작성해준다.

     

    cargorust의 의존성관리 도구이다. java의 경험이 있다면 maven 혹은 gradle이라고 생각하면 된다. 경험이 없다면 지금은 외부에서 만든 라이브러리를 손쉽게 내 프로젝트에 설치하는 도구라고 보면 된다.

     

    이제 rustup을 설치해보자. 터미널에 다음을 입력한다.

    $ curl https://sh.rustup.rs -sSf | sh

     

    그럼 다음과 같은 글들이 출력이 된다.

    # ...
    info: downloading installer
    
    Welcome to Rust!
    
    This will download and install the official compiler for the Rust
    programming language, and its package manager, Cargo.
    
    Rustup metadata and toolchains will be installed into the Rustup
    home directory, located at:
    
      /Users/gurumee/.rustup
    
    This can be modified with the RUSTUP_HOME environment variable.
    
    The Cargo home directory located at:
    
      /Users/gurumee/.cargo
    
    This can be modified with the CARGO_HOME environment variable.
    
    The cargo, rustc, rustup and other commands will be added to
    Cargo's bin directory, located at:
    
      /Users/gurumee/.cargo/bin
    
    This path will then be added to your PATH environment variable by
    modifying the profile files located at:
    
      /Users/gurumee/.profile
      /Users/gurumee/.bash_profile
      /Users/gurumee/.zshenv
    
    You can uninstall at any time with rustup self uninstall and
    these changes will be reverted.
    
    Current installation options:
    
    
       default host triple: x86_64-apple-darwin
         default toolchain: stable (default)
                   profile: default
      modify PATH variable: yes
    
    1) Proceed with installation (default)
    2) Customize installation
    3) Cancel installation

     

    "1" 입력 후 엔터 혹은 그냥 엔터를 누르면 설치가 된다. 그리고 다음 문구가 출력되게 된다.

    # ...
    Rust is installed now. Great!
    
    To get started you may need to restart your current shell.
    This would reload your PATH environment variable to include
    Cargo's bin directory ($HOME/.cargo/bin).
    
    To configure your current shell, run:
    source $HOME/.cargo/env

     

    여기서 cargo를 터미널에서 사용하기 위해서는 추가적으로 다음 명령어를 입력해주어야 한다.

    $ source $HOME/.cargo/env

     

    그 후 터미널에 다음을 입력해서 각각 잘 동작하는지 확인한다.

    # rustup 버전 확인
    $ rustup --version
    rustup 1.24.3 (ce5817a94 2021-05-31)
    info: This is the version for the rustup toolchain manager, not the rustc compiler.
    info: The currently active `rustc` version is `rustc 1.58.1 (db9d1b20b 2022-01-20)`
    
    # cargo 버전 확인
    $ cargo --version
    cargo 1.58.0 (f01b232bc 2022-01-19)

    Hello, World! 프로그램 만들고 실행하기

    이제 터미널에 다음을 입력하여 프로젝트 루트 디렉토리를 만든다.

    # hello_world 디렉토리 생성
    $ mkdir hello_world 
    
    # hello_world 디렉토리 이동
    $ cd hello_world 

    그 후 main.rs를 다음과 같이 생성한다. .rsrust 코드로 작성된 파일의 확장자이다.

     

    hello_world/main.rs

    fn main() {
        println!("Hello, world!");
    }

     

    이제 rustc로 이 파일을 컴파일해보자.

    $ rustc main.rs

     

    그러면, main이라는 실행 파일이 생길 것이다.

    $ ls -al
    total 912
    drwxr-xr-x  4 gurumee  staff     128  2 19 20:43 .
    drwxr-xr-x  5 gurumee  staff     160  2 19 20:43 ..
    -rwxr-xr-x  1 gurumee  staff  461752  2 19 20:43 main     # 왼쪽에 x가 실행 파일이라는 의미이다.
    -rw-r--r--  1 gurumee  staff      45  2 19 20:43 main.rs

     

    이제 main을 실행시켜보자.

    $ ./main
    Hello, world!

    Hello, World! 프로그램 분석하기

    "Hello, World!" 프로그램을 분석해보자. 전체 코드를 다시 한 번 살펴보자.

    fn main() {
        println!("Hello, world!");
    }

     

    여기서 fn은 함수를 의미한다. main은 함수 명이다. main이란 함수는 정말 특별한 함수이다. 바로 프로그램의 진입점이 되는 함수이기 때문이다. 실행파일을 실행시키면 제일 먼저 이 main 함수가 실행이 된다. 함수를 정의하고 사용하는 자세한 방법은 추후에 다른 문서에서 다루도록 하겠다.

     

    이제 main 함수 안쪽 부분을 살펴보자.

        println!("Hello, world!");

     

    이 부분에서 살펴볼 점은 크게 4가지이다.

     

    (1) 빈 공간은 탭이 아니라 4개의 스페이스이다.
    (2) println!은 매크로이다. 함수였다면 println으로 호출했을 것이다. 일반적으로 "!"가 붙으면 매크로임을 명시한다.
    (3) "Hello, world!"는 문자열 타입(string)이다. println! 매크로는 인자로 문자열 타입을 받는다.
    (4) 라인 끝에 ;로 끝난다. 이는 표현식이 끝남을 의미한다.

     

    이런 소스 코드를 작성하는 과정을 거친 후 `rustc` 컴파일러 혹은 `cargo`를 이용해서 컴파일 및 빌드를 진행하면 우리가 작성한 프로그램이 동작하는 실행 파일을 얻을 수 있다.

    참고

Designed by Tistory.