RustBook - 1. getting started

숲사람·2022년 3월 23일
0

Rust

목록 보기
1/15
post-thumbnail

이 시리즈는 Rust Book을 공부하고 정리한 문서입니다. 댓글로 많은 조언 부탁드립니다.
Rust Book: https://doc.rust-lang.org/book/

0. RUST 란

환경적 측면에서 파이썬화 시킨 c 또는 cpp 라고 볼수 있을듯? c와 다르게 cargo 라는 마치 pip같은 패키지 매니저가 존재한다. 게다가 시스템 유틸리티를 c나 cpp 수준의 성능으로 만들 수 있다. cpp 대신에 rust를 배워보자

1. 환경구축

Ubuntu 16.04 or macOS

1.1 설치

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

rustc rust-std cargo rust-docs 등을 설치함
Cargo는 Rust's package manager 이다.
$HOME/.cargo/bin 경로에 실행파일이 있음.
$HOME/.rustup 환경설정 경로? toolchain도 있음.
$PATH$HOME/.profile 에 등록됨.

1.2 Hello World

  • 프로젝트 경로 생성
 $ mkdir -p projects/hello_world && cd projects/hello_world
  • 컴파일 with rustc
 $ rustc main.rs

main 이라는 ELF executable 파일 생성

  • Execute
 $ ./main
Hello, World!
  • main.rs
fn main() {
    println!("Hello, world!");
}
  • {} rust는 함수에 { 가 필요. 코딩스타일 가이드는 함수명과 {를 같은라인에
  • rustfmt 는 코딩스타일 체크 툴이다.
  • indent 는 4 space 이다. tab아님. (그런데 tab써도 컴파일&동작은 됨..)
  • ; 로 라인의 끝을 명시한다.
  • plintln 은 Rust Macro 라고 불리고 기본 내장 매크로 함수이다.

1.3 Hello Cargo

Cargo는 Rust의 Build시스템이자 Package Manager이다. hello world 예제에서는 디펜던시가 필요한 라이브러리등을 사용하지 않아서 rustc로 간단하게 컴파일 했지만, 소스코드가 복잡해지면 디펜던시를 추가해야하고 이것을 cargo를 통해 빌드하면 간단하게 할수 있다.

1.3.1 Cargo로 프로젝트 생성

$ cargo new hello_cargo
$ cd hello_cargo
hello_cargo$ tree -a -L 1
├── Cargo.toml
├── .git
├── .gitignore
└── src
     └── main.rs

src/ 파일 디렉터리 및 Cargo.toml config파일 및 git init까지 해준다.
최상위 경로에는 README files, license information, configuration files, 어쨋든 소스코드와 관련없는것을 포함하기를 추천. 소스코드는 모두 src/ 아래로.

  • Cargo.toml
[package]
name = "hello_cargo"
version = "0.1.0"
authors = ["Ji-Hun Kim <jihuun.k@gmail.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

참고로 TOML (Tom’s Obvious, Minimal Language) format 을 rust 설정 포맷으로 채택했음.
[package] 컴파일시 필요한 정보 기록
[dependencies]

1.3.2 Cargo로 빌드 및 실행하기

  • cargo build
$ cargo build
   Compiling hello_cargo v0.1.0 (/home/jihuun/project/rust/projects/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.31s

실행파일은 ./target/debug/hello_cargo 에 생성된다.

$ ./target/debug/hello_cargo 
Hello, world!
  • cargo run

cargo build & 실행 대신에 cargo run 하면 빌드 및 실행까지 한번에 됨

$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/hello_cargo`
Hello, world!
  • cargo check

cargo build 와 다르게 실행파일을 생성하지 않으면서 컴파일에 성공하는지 빠르게 체크해주는 옵션. 따라서 cargo build를 하기전에 먼저 cargo check 를 해보를 추천.

$ cargo check
    Checking hello_cargo v0.1.0 (/home/jihuun/project/rust/projects/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.07s

위에서 cargo build는 0.31s 걸렸는데 check는 0.07s 걸림

1.3.3. 릴리즈용 빌드

$ cargo build --release

이 옵션은 실행파일은 target/debug/ 가 아닌 target/release/ 에 생성한다. 그리고 Optimization 옵션도 추가된다. (gcc -O 같은). 실행파일 속도가 더 빠름.

cargo 가 관리하는 세가지

  • building your code
  • downloading the libraries your code depends on
  • building those libraries

2 Trouble shoot

  • cargo run 시 SSL 에러 발생(curl) -> proxy문제
    ~/.cargo/config 에 아래와 같이 proxy 를 추가한다.
[http]
proxy = "http://111.222.333.000:8000"

에러 로그

 $ cargo run                                                
    Updating crates.io index
warning: spurious network error (2 tries remaining): [35] SSL connect error; class=Net (12)
warning: spurious network error (1 tries remaining): [35] SSL connect error; class=Net (12)
error: failed to load source for a dependency on `reqwest`

Caused by:
  Unable to update registry `https://github.com/rust-lang/crates.io-index`

Caused by:
  failed to fetch `https://github.com/rust-lang/crates.io-index`

Caused by:
  [35] SSL connect error; class=Net (12)
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글