상세 컨텐츠

본문 제목

25. Rust Cargo 패키지 관리자

Rust를 처음부터 배우세요

by 러스트코리아 2024. 12. 22. 01:56

본문

반응형

Rust에는 내장 패키지 관리자 있습니다 . Rust 설치와 함께 설치됩니다.

cargo는 Python의 pip, Ruby의 RubyGems, Node.js의 NPM과 유사합니다.

물론, cargo는 단순한 패키지 관리자가 아니라 Rust의 프로젝트 관리 도구이기도 합니다.

25.1 cargo 설치 여부 및  버전 확인

터미널이나 명령줄 프롬프트 또는 셸을 열고 다음 명령을 입력하고 Enter를 누릅니다.

  1. cargo --version

이미 설치되어 있는 경우 출력은 다음과 유사합니다.

  1. cargo 1.35.0

cargo 패키지 관리자와 Rust 언어의 버전이 동기화됩니다.

25.2 cargo에 대한 도움말 정보

cargo의 도움말 정보를 보거나 화물이 제공하는 명령과 기능을 확인하려면 터미널에 화물 또는 화물 -h를 입력하고 Enter를 누르면 됩니다.

출력은 다음과 유사합니다.

  1. Rust's package manager
  2.  
  3. USAGE:
  4. cargo [OPTIONS] [SUBCOMMAND]
  5.  
  6. OPTIONS:
  7. -V, --version Print version info and exit
  8. --list List installed commands
  9. --explain <CODE> Run `rustc --explain CODE`
  10. -v, --verbose Use verbose output (-vv very verbose/build.rs output)
  11. -q, --quiet No output printed to stdout
  12. --color <WHEN> Coloring: auto, always, never
  13. --frozen Require Cargo.lock and cache are up to date
  14. --locked Require Cargo.lock is up to date
  15. -Z <FLAG>... Unstable (nightly-only) flags to Cargo, see 'cargo -Z help' for details
  16. -h, --help Prints help information
  17.  
  18. Some common cargo commands are (see all commands with --list):
  19. build Compile the current package
  20. check Analyze the current package and report errors, but don't build object files
  21. clean Remove the target directory
  22. doc Build this package's and its dependencies' documentation
  23. new Create a new cargo package
  24. init Create a new cargo package in an existing directory
  25. run Run a binary or example of the local package
  26. test Run the tests
  27. bench Run the benchmarks
  28. update Update dependencies listed in Cargo.lock
  29. search Search registry for crates
  30. publish Package and upload this package to the registry
  31. install Install a Rust binary. Default location is $HOME/.cargo/bin
  32. uninstall Uninstall a Rust binary
  33.  
  34. See 'cargo help <command>' for more information on a specific command.

25.3 cargo가 제공하는 명령어

위의 cargo 도움말 정보에 설명된 것처럼 cargo에서 제공하는 명령어를 모두 보고 싶다면 터미널에 직접 입력하면 됩니다.

  1. cargo --list

출력은 다음과 같습니다

  1. Installed Commands:
  2. bench Execute all benchmarks of a local package
  3. build Compile a local package and all of its dependencies
  4. check Check a local package and all of its dependencies for errors
  5. clean Remove artifacts that cargo has generated in the past
  6. clippy-preview Checks a package to catch common mistakes and improve your Rust code.
  7. doc Build a package's documentation
  8. fetch Fetch dependencies of a package from the network
  9. fix Automatically fix lint warnings reported by rustc
  10. generate-lockfile Generate the lockfile for a package
  11. git-checkout Checkout a copy of a Git repository
  12. init Create a new cargo package in an existing directory
  13. install Install a Rust binary. Default location is $HOME/.cargo/bin
  14. locate-project Print a JSON representation of a Cargo.toml file's location
  15. login Save an api token from the registry locally. If token is not specified, it will be read from stdin.
  16. metadata Output the resolved dependencies of a package, the concrete used versions including overrides, in machine-readable format
  17. new Create a new cargo package at <path>
  18. owner Manage the owners of a crate on the registry
  19. package Assemble the local package into a distributable tarball
  20. pkgid Print a fully qualified package specification
  21. publish Upload a package to the registry
  22. read-manifest Print a JSON representation of a Cargo.toml manifest.
  23. run Run a binary or example of the local package
  24. rustc Compile a package and all of its dependencies
  25. rustdoc Build a package's documentation, using specified custom flags.
  26. search Search packages in crates.io
  27. test Execute all unit and integration tests and build examples of a local package
  28. uninstall Remove a Rust binary
  29. update Update dependencies as recorded in the local lock file
  30. verify-project Check correctness of crate manifest
  31. version Show version information
  32. yank Remove a pushed crate from the index

명령어가 많아서 하나씩 소개하지는 않겠습니다. 자주 사용되는 명령어 몇 가지만 소개하겠습니다.

주문하다설명하다

명령어 설명
cargo build 현재 프로젝트 컴파일
cargo check 현재 프로젝트를 분석하고 프로젝트의 오류를 보고하지만 프로젝트 파일은 컴파일하지 않습니다.
cargo run src/main.rs 파일을 컴파일하고 실행합니다.
cargo clean 현재 프로젝트 아래의 대상 디렉터리와 해당 디렉터리의 모든 하위 디렉터리 및 파일을 제거합니다.
cargo update 현재 프로젝트의 Cargo.lock 파일에 나열된 모든 종속성을 업데이트합니다.
cargo new 현재 디렉터리에 새 화물 프로젝트를 생성합니다.

특정 명령어에 익숙하지 않은 경우 바로 화물 도움말을 사용할 수 있습니다.구문은 명령에 대한 도움말 정보를 표시합니다.

예를 들어, new 명령에 대해 자세히 알아보려면 화물 도움말를 직접 입력하면 다음과 같이 출력됩니다.

  1. cargo-new
  2. Create a new cargo package at <path>
  3.  
  4. USAGE:
  5. cargo new [OPTIONS] <path>
  6.  
  7. OPTIONS:
  8. -q, --quiet No output printed to stdout
  9. --registry <REGISTRY> Registry to use
  10. --vcs <VCS> Initialize a new repository for the given version control system (git, hg, pijul, or
  11. fossil) or do not initialize any version control at all (none), overriding a global
  12. configuration. [possible values: git, hg, pijul, fossil, none]
  13. --bin Use a binary (application) template [default]
  14. --lib Use a library template
  15. --edition <YEAR> Edition to set for the crate generated [possible values: 2015, 2018]
  16. --name <NAME> Set the resulting package name, defaults to the directory name
  17. -v, --verbose Use verbose output (-vv very verbose/build.rs output)
  18. --color <WHEN> Coloring: auto, always, never
  19. --frozen Require Cargo.lock and cache are up to date
  20. --locked Require Cargo.lock is up to date
  21. -Z <FLAG>... Unstable (nightly-only) flags to Cargo, see 'cargo -Z help' for details
  22. -h, --help Prints help information
  23.  
  24. ARGS:
  25. <path>

25.4 Cargo는 Rust 프로젝트를 생성합니다

패키지 관리자로서 화물은 타사 라이브러리를 다운로드하는 데 도움을 줄 수 있습니다. 그러나 이는 cargo가 할 수 있는 일 중 빙산의 일각에 불과합니다.

또한 cargo를 사용하여 자체 라이브러리를 구축한 다음 이를 Cargo의 공식 창고에 게시할 수 있습니다.

Cargo는 실행 가능한 바이너리  라이브러리라는 두 가지 유형의 프로젝트를 생성할 수 있습니다 .

실행 가능한 바이너리 프로그램을 생성하려면 아래의 Cargo new 명령을 사용하여 프로젝트를 생성할 수 있습니다.

  1. cargo new project_name --bin

라이브러리를 생성하려면 아래의 Cargo new 명령을 사용하면 됩니다.

  1. cargo new project_name --lib

25.5 예: Cargo를 사용하여 완전한 바이너리 실행 프로그램 프로젝트를 생성하고 빌드합니다.

프로젝트 생성, 종속성 설치 및 프로젝트 컴파일은 패키지 관리자로서 화물의 가장 중요한 세 가지 기능입니다.

아래에서는 간단한 게임을 사용하겠습니다. 숫자를 추측하여 프로젝트를 생성하고 컴파일하기 위해 화물을 사용하는 방법을 보여줍니다.

1. 프로젝트 디렉토리 생성

터미널이나 명령줄 프롬프트 또는 셸을 열고 프로젝트를 넣을 디렉터리로 이동합니다.

그런 다음 화물 새 추측 게임 -bin 명령을 입력합니다. 예상치 못한 일이 발생하지 않으면 다음 프롬프트가 출력됩니다.

  1. $ cargo new guess-game-app --bin
  2. Created binary (application) `guess-game-app` package

위의 프롬프트가 나타나면서 프로젝트가 성공적으로 생성되었음을 나타냅니다. 동시에 이 명령은 현재 디렉토리에 새로운 추측-게임-app 디렉토리를 생성하고 필요한 파일을 생성합니다.

  1. $ tree guess-game-app/
  2. guess-game-app/
  3. ├── Cargo.toml
  4. └── src
  5. └── main.rs

위에서 볼 수 있듯이, Cargo new 명령은 새 프로젝트를 생성하는 데 사용되며 --bin 옵션은 현재 프로젝트가 실행 가능한 바이너리 프로그램 프로젝트임을 나타내는 데 사용됩니다.

Cargo에서는 프로젝트를 보통 crates라고 부르는데, 왜 그런지 모르겠네요...

Rust는 공식적으로 cargo 패키지 관리자를 위한 중앙 호스팅 웹사이트를 제공합니다. 홈페이지 주소는 https://crates.io/입니다. 이 웹사이트에서 필요한 타사 라이브러리나 유용한 타사 프로젝트를 찾을 수 있습니다.

2. 프로젝트에 필요한 타사 종속 라이브러리 추가

숫자 추측 게임 에서는 난수를 생성해야 합니다. 그러나 Rust 언어 코어나 Rust 표준 라이브러리는 난수 생성을 위한 방법이나 구조를 제공하지 않습니다.

우리는 https://crates.io/ 에서 다른 개발자가 제공한 타사 라이브러리나 크레이트 에만 의존할 수 있습니다 .

crates.io 웹사이트를 열고 상단 검색창에 rand를 입력한 후 Enter 키를 누르면 타사 난수 생성 라이브러리를 찾을 수 있습니다.

검색결과를 보면 난수생성 관련 라이브러리가 많이 나오는데 저희는 rand만 사용하고 있습니다.

검색 결과에서 rand를 클릭하면 https://crates.io/crates/rand로 이동합니다.

아래 그림은 우리가 필요로 하는 난수생성 라이브러리 rand의 기본정보를 스크린샷으로 나타낸 것입니다 .

rand의 기본 정보를 이해한 후 Cargo.toml을 수정하여 rand 종속성을 추가할 수 있습니다.

정확하게 말하면 [종속성] 섹션에 rand = "0.6.5"를 추가하세요.

편집된 파일의 내용은 다음과 같습니다

  1. [package]
  2. name = "guess-game-app"
  3. version = "0.1.0"
  4. authors = ["** <noreply@xxx.com>"]
  5. edition = "2018"
  6.  
  7. [dependencies]
  8. rand = "0.6.5"

3. 먼저 프로젝트를 미리 컴파일하세요.

Rust/C/C++와 같은 정적 언어의 경우 먼저 미리 컴파일하는 습관이 필요합니다.

사전 컴파일 중에 프로젝트 구성이 올바른지 알려주고 타사 라이브러리도 다운로드하므로 자동으로 메시지를 표시할 수 있기 때문입니다.

카고를 사용하여 생성된 프로젝트의 경우 터미널에 카고 빌드를 입력하여 프로젝트를 사전 컴파일할 수 있습니다.

출력은 일반적으로 다음과 같습니다

  1. Updating crates.io index
  2. Downloaded rand v0.6.5
  3. Downloaded libc v0.2.58
  4. Downloaded rand_core v0.4.0
  5. Downloaded rand_hc v0.1.0
  6. Downloaded rand_chacha v0.1.1
  7. Downloaded rand_isaac v0.1.1
  8. Downloaded rand_jitter v0.1.4
  9. Downloaded rand_os v0.1.3
  10. Downloaded rand_xorshift v0.1.1
  11. Downloaded rand_pcg v0.1.2
  12. Downloaded autocfg v0.1.4
  13. Downloaded rand_core v0.3.1
  14. Compiling libc v0.2.58
  15. Compiling autocfg v0.1.4
  16. Compiling rand_core v0.4.0
  17. Compiling rand_core v0.3.1
  18. Compiling rand_isaac v0.1.1
  19. Compiling rand_xorshift v0.1.1
  20. Compiling rand_hc v0.1.0
  21. Compiling rand_pcg v0.1.2
  22. Compiling rand_chacha v0.1.1
  23. Compiling rand v0.6.5
  24. Compiling rand_os v0.1.3
  25. Compiling rand_jitter v0.1.4
  26. Compiling guess-game-app v0.1.0 (/Users/Admin/Downloads/guess-game-app)
  27. Finished dev [unoptimized + debuginfo] target(s) in 45.77s

미리 컴파일된 출력 정보에서 rand 타사 라이브러리 및 관련 종속성이 자동으로 다운로드되는 것을 확인할 수 있습니다.

4. 숫자 추측 게임의 논리를 이해합니다.

코딩을 시작하기 전에 먼저 숫자 추측 게임의 게임 로직을 분석해 보겠습니다.

이것은 좋은 프로그래밍 습관입니다.

  1. 게임이 시작되면 숫자 N이 무작위로 생성됩니다.
  2. 그런 다음 몇 가지 정보를 출력하여 사용자에게 메시지를 표시하고 사용자가 생성된 숫자 N을 추측하고 입력하도록 합니다.
  3. 사용자가 입력한 숫자가 임의의 숫자보다 작으면 사용자에게 너무 낮음 메시지가 표시되고 사용자가 계속 추측할 수 있습니다.
  4. 사용자가 입력한 숫자가 임의의 숫자보다 크면 너무 높음에 대한 프롬프트가 표시되고 사용자가 계속 추측할 수 있습니다.
  5. 사용자가 입력한 숫자가 우연히 난수인 경우 게임이 종료되고 You go it...이 출력됩니다.

5. main.rs 파일을 수정하여 게임 로직 개선

숫자 추측 게임의 논리는 매우 간단합니다. 이전에 자세히 분석한 다음, 위의 논리만 구현하면 됩니다.

코드를 소개하지 않고 복사해서 붙여넣기만 하면 됩니다.

  1. use std::io;
  2. extern crate rand; // 현재 프로젝트에서 Rand 타사 라이브러리 가져오기
  3.  
  4. use rand::random;
  5. fn get_guess() -> u8 {
  6. loop {
  7. println!("Input guess") ;
  8. let mut guess = String::new();
  9. io::stdin().read_line(&mut guess)
  10. .expect("could not read from stdin");
  11. match guess.trim().parse::<u8>(){ // 입력 시작과 끝의 공백을 제거해야 합니다.
  12. Ok(v) => return v,
  13. Err(e) => println!("could not understand input {}",e)
  14. }
  15. }
  16. }
  17. fn handle_guess(guess:u8,correct:u8)-> bool {
  18. if guess < correct {
  19. println!("Too low");
  20. false
  21.  
  22. } else if guess> correct {
  23. println!("Too high");
  24. false
  25. } else {
  26. println!("You go it ..");
  27. true
  28. }
  29. }
  30. fn main() {
  31. println!("Welcome to no guessing game");
  32.  
  33. let correct:u8 = random();
  34. println!("correct value is {}",correct);
  35. loop {
  36. let guess = get_guess();
  37. if handle_guess(guess,correct){
  38. break;
  39. }
  40. }
  41. }

6. 프로젝트를 컴파일하고 실행 파일을 실행합니다.

터미널에 Cargo Run을 입력하여 추측 게임을 컴파일하고 실행할 수 있습니다.

오류가 없다면 그냥 게임 몇 개만 하면 됩니다 ㅎㅎ

  1. Compiling guess-game-app v0.1.0 (/Users/Admin/Downloads/guess-game-app)
  2. Finished dev [unoptimized + debuginfo] target(s) in 0.67s
  3. Running `target/debug/guess-game-app`
  4. Welcome to no guessing game
  5. correct value is 145
  6. Input guess
  7. 20
  8. Too low
  9. Input guess
  10. 100
  11. Too low
  12. Input guess
  13. 97
  14. Too low
  15. Input guess
  16. 145
  17. You go it ..
현재 콘텐츠 저작권은 chapin666 또는 그 계열사에 있습니다.
반응형

'Rust를 처음부터 배우세요' 카테고리의 다른 글

24. Rust 파일 읽기 및 쓰기  (0) 2024.12.22
23. Rust IO  (0) 2024.12.21
22. Rust 제네릭  (0) 2024.12.21
21. Rust 오류 처리  (0) 2024.12.21
20. Rust 컬렉션  (0) 2024.12.14

관련글 더보기