Rust에는 내장 패키지 관리자가 있습니다 . Rust 설치와 함께 설치됩니다.
cargo는 Python의 pip, Ruby의 RubyGems, Node.js의 NPM과 유사합니다.
물론, cargo는 단순한 패키지 관리자가 아니라 Rust의 프로젝트 관리 도구이기도 합니다.
25.1 cargo 설치 여부 및 버전 확인
터미널이나 명령줄 프롬프트 또는 셸을 열고 다음 명령을 입력하고 Enter를 누릅니다.
- cargo --version
이미 설치되어 있는 경우 출력은 다음과 유사합니다.
- cargo 1.35.0
cargo 패키지 관리자와 Rust 언어의 버전이 동기화됩니다.
25.2 cargo에 대한 도움말 정보
cargo의 도움말 정보를 보거나 화물이 제공하는 명령과 기능을 확인하려면 터미널에 화물 또는 화물 -h를 입력하고 Enter를 누르면 됩니다.
출력은 다음과 유사합니다.
- Rust's package manager
-
- USAGE:
- cargo [OPTIONS] [SUBCOMMAND]
-
- OPTIONS:
- -V, --version Print version info and exit
- --list List installed commands
- --explain <CODE> Run `rustc --explain CODE`
- -v, --verbose Use verbose output (-vv very verbose/build.rs output)
- -q, --quiet No output printed to stdout
- --color <WHEN> Coloring: auto, always, never
- --frozen Require Cargo.lock and cache are up to date
- --locked Require Cargo.lock is up to date
- -Z <FLAG>... Unstable (nightly-only) flags to Cargo, see 'cargo -Z help' for details
- -h, --help Prints help information
-
- Some common cargo commands are (see all commands with --list):
- build Compile the current package
- check Analyze the current package and report errors, but don't build object files
- clean Remove the target directory
- doc Build this package's and its dependencies' documentation
- new Create a new cargo package
- init Create a new cargo package in an existing directory
- run Run a binary or example of the local package
- test Run the tests
- bench Run the benchmarks
- update Update dependencies listed in Cargo.lock
- search Search registry for crates
- publish Package and upload this package to the registry
- install Install a Rust binary. Default location is $HOME/.cargo/bin
- uninstall Uninstall a Rust binary
-
- See 'cargo help <command>' for more information on a specific command.
25.3 cargo가 제공하는 명령어
위의 cargo 도움말 정보에 설명된 것처럼 cargo에서 제공하는 명령어를 모두 보고 싶다면 터미널에 직접 입력하면 됩니다.
- cargo --list
출력은 다음과 같습니다
- Installed Commands:
- bench Execute all benchmarks of a local package
- build Compile a local package and all of its dependencies
- check Check a local package and all of its dependencies for errors
- clean Remove artifacts that cargo has generated in the past
- clippy-preview Checks a package to catch common mistakes and improve your Rust code.
- doc Build a package's documentation
- fetch Fetch dependencies of a package from the network
- fix Automatically fix lint warnings reported by rustc
- generate-lockfile Generate the lockfile for a package
- git-checkout Checkout a copy of a Git repository
- init Create a new cargo package in an existing directory
- install Install a Rust binary. Default location is $HOME/.cargo/bin
- locate-project Print a JSON representation of a Cargo.toml file's location
- login Save an api token from the registry locally. If token is not specified, it will be read from stdin.
- metadata Output the resolved dependencies of a package, the concrete used versions including overrides, in machine-readable format
- new Create a new cargo package at <path>
- owner Manage the owners of a crate on the registry
- package Assemble the local package into a distributable tarball
- pkgid Print a fully qualified package specification
- publish Upload a package to the registry
- read-manifest Print a JSON representation of a Cargo.toml manifest.
- run Run a binary or example of the local package
- rustc Compile a package and all of its dependencies
- rustdoc Build a package's documentation, using specified custom flags.
- search Search packages in crates.io
- test Execute all unit and integration tests and build examples of a local package
- uninstall Remove a Rust binary
- update Update dependencies as recorded in the local lock file
- verify-project Check correctness of crate manifest
- version Show version information
- 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 명령에 대해 자세히 알아보려면 화물 도움말를 직접 입력하면 다음과 같이 출력됩니다.
- cargo-new
- Create a new cargo package at <path>
-
- USAGE:
- cargo new [OPTIONS] <path>
-
- OPTIONS:
- -q, --quiet No output printed to stdout
- --registry <REGISTRY> Registry to use
- --vcs <VCS> Initialize a new repository for the given version control system (git, hg, pijul, or
- fossil) or do not initialize any version control at all (none), overriding a global
- configuration. [possible values: git, hg, pijul, fossil, none]
- --bin Use a binary (application) template [default]
- --lib Use a library template
- --edition <YEAR> Edition to set for the crate generated [possible values: 2015, 2018]
- --name <NAME> Set the resulting package name, defaults to the directory name
- -v, --verbose Use verbose output (-vv very verbose/build.rs output)
- --color <WHEN> Coloring: auto, always, never
- --frozen Require Cargo.lock and cache are up to date
- --locked Require Cargo.lock is up to date
- -Z <FLAG>... Unstable (nightly-only) flags to Cargo, see 'cargo -Z help' for details
- -h, --help Prints help information
-
- ARGS:
- <path>
25.4 Cargo는 Rust 프로젝트를 생성합니다
패키지 관리자로서 화물은 타사 라이브러리를 다운로드하는 데 도움을 줄 수 있습니다. 그러나 이는 cargo가 할 수 있는 일 중 빙산의 일각에 불과합니다.
또한 cargo를 사용하여 자체 라이브러리를 구축한 다음 이를 Cargo의 공식 창고에 게시할 수 있습니다.
Cargo는 실행 가능한 바이너리 와 라이브러리라는 두 가지 유형의 프로젝트를 생성할 수 있습니다 .
실행 가능한 바이너리 프로그램을 생성하려면 아래의 Cargo new 명령을 사용하여 프로젝트를 생성할 수 있습니다.
- cargo new project_name --bin
라이브러리를 생성하려면 아래의 Cargo new 명령을 사용하면 됩니다.
- cargo new project_name --lib
25.5 예: Cargo를 사용하여 완전한 바이너리 실행 프로그램 프로젝트를 생성하고 빌드합니다.
프로젝트 생성, 종속성 설치 및 프로젝트 컴파일은 패키지 관리자로서 화물의 가장 중요한 세 가지 기능입니다.
아래에서는 간단한 게임을 사용하겠습니다. 숫자를 추측하여 프로젝트를 생성하고 컴파일하기 위해 화물을 사용하는 방법을 보여줍니다.
1. 프로젝트 디렉토리 생성
터미널이나 명령줄 프롬프트 또는 셸을 열고 프로젝트를 넣을 디렉터리로 이동합니다.
그런 다음 화물 새 추측 게임 -bin 명령을 입력합니다. 예상치 못한 일이 발생하지 않으면 다음 프롬프트가 출력됩니다.
- $ cargo new guess-game-app --bin
- Created binary (application) `guess-game-app` package
위의 프롬프트가 나타나면서 프로젝트가 성공적으로 생성되었음을 나타냅니다. 동시에 이 명령은 현재 디렉토리에 새로운 추측-게임-app 디렉토리를 생성하고 필요한 파일을 생성합니다.
- $ tree guess-game-app/
- guess-game-app/
- ├── Cargo.toml
- └── src
- └── 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"를 추가하세요.
편집된 파일의 내용은 다음과 같습니다
- [package]
- name = "guess-game-app"
- version = "0.1.0"
- authors = ["** <noreply@xxx.com>"]
- edition = "2018"
-
- [dependencies]
- rand = "0.6.5"
3. 먼저 프로젝트를 미리 컴파일하세요.
Rust/C/C++와 같은 정적 언어의 경우 먼저 미리 컴파일하는 습관이 필요합니다.
사전 컴파일 중에 프로젝트 구성이 올바른지 알려주고 타사 라이브러리도 다운로드하므로 자동으로 메시지를 표시할 수 있기 때문입니다.
카고를 사용하여 생성된 프로젝트의 경우 터미널에 카고 빌드를 입력하여 프로젝트를 사전 컴파일할 수 있습니다.
출력은 일반적으로 다음과 같습니다
- Updating crates.io index
- Downloaded rand v0.6.5
- Downloaded libc v0.2.58
- Downloaded rand_core v0.4.0
- Downloaded rand_hc v0.1.0
- Downloaded rand_chacha v0.1.1
- Downloaded rand_isaac v0.1.1
- Downloaded rand_jitter v0.1.4
- Downloaded rand_os v0.1.3
- Downloaded rand_xorshift v0.1.1
- Downloaded rand_pcg v0.1.2
- Downloaded autocfg v0.1.4
- Downloaded rand_core v0.3.1
- Compiling libc v0.2.58
- Compiling autocfg v0.1.4
- Compiling rand_core v0.4.0
- Compiling rand_core v0.3.1
- Compiling rand_isaac v0.1.1
- Compiling rand_xorshift v0.1.1
- Compiling rand_hc v0.1.0
- Compiling rand_pcg v0.1.2
- Compiling rand_chacha v0.1.1
- Compiling rand v0.6.5
- Compiling rand_os v0.1.3
- Compiling rand_jitter v0.1.4
- Compiling guess-game-app v0.1.0 (/Users/Admin/Downloads/guess-game-app)
- Finished dev [unoptimized + debuginfo] target(s) in 45.77s
미리 컴파일된 출력 정보에서 rand 타사 라이브러리 및 관련 종속성이 자동으로 다운로드되는 것을 확인할 수 있습니다.
4. 숫자 추측 게임의 논리를 이해합니다.
코딩을 시작하기 전에 먼저 숫자 추측 게임의 게임 로직을 분석해 보겠습니다.
이것은 좋은 프로그래밍 습관입니다.
- 게임이 시작되면 숫자 N이 무작위로 생성됩니다.
- 그런 다음 몇 가지 정보를 출력하여 사용자에게 메시지를 표시하고 사용자가 생성된 숫자 N을 추측하고 입력하도록 합니다.
- 사용자가 입력한 숫자가 임의의 숫자보다 작으면 사용자에게 너무 낮음 메시지가 표시되고 사용자가 계속 추측할 수 있습니다.
- 사용자가 입력한 숫자가 임의의 숫자보다 크면 너무 높음에 대한 프롬프트가 표시되고 사용자가 계속 추측할 수 있습니다.
- 사용자가 입력한 숫자가 우연히 난수인 경우 게임이 종료되고 You go it...이 출력됩니다.
5. main.rs 파일을 수정하여 게임 로직 개선
숫자 추측 게임의 논리는 매우 간단합니다. 이전에 자세히 분석한 다음, 위의 논리만 구현하면 됩니다.
코드를 소개하지 않고 복사해서 붙여넣기만 하면 됩니다.
- use std::io;
- extern crate rand; // 현재 프로젝트에서 Rand 타사 라이브러리 가져오기
-
- use rand::random;
- fn get_guess() -> u8 {
- loop {
- println!("Input guess") ;
- let mut guess = String::new();
- io::stdin().read_line(&mut guess)
- .expect("could not read from stdin");
- match guess.trim().parse::<u8>(){ // 입력 시작과 끝의 공백을 제거해야 합니다.
- Ok(v) => return v,
- Err(e) => println!("could not understand input {}",e)
- }
- }
- }
- fn handle_guess(guess:u8,correct:u8)-> bool {
- if guess < correct {
- println!("Too low");
- false
-
- } else if guess> correct {
- println!("Too high");
- false
- } else {
- println!("You go it ..");
- true
- }
- }
- fn main() {
- println!("Welcome to no guessing game");
-
- let correct:u8 = random();
- println!("correct value is {}",correct);
- loop {
- let guess = get_guess();
- if handle_guess(guess,correct){
- break;
- }
- }
- }
6. 프로젝트를 컴파일하고 실행 파일을 실행합니다.
터미널에 Cargo Run을 입력하여 추측 게임을 컴파일하고 실행할 수 있습니다.
오류가 없다면 그냥 게임 몇 개만 하면 됩니다 ㅎㅎ
- Compiling guess-game-app v0.1.0 (/Users/Admin/Downloads/guess-game-app)
- Finished dev [unoptimized + debuginfo] target(s) in 0.67s
- Running `target/debug/guess-game-app`
- Welcome to no guessing game
- correct value is 145
- Input guess
- 20
- Too low
- Input guess
- 100
- Too low
- Input guess
- 97
- Too low
- Input guess
- 145
- You go it ..
현재 콘텐츠 저작권은 chapin666 또는 그 계열사에 있습니다.