手机搭建本地网站建设部安全员证书查询网站
文章目录
- 一、Rust的编译器rustc
 - 二、开发环境搭建
 - 三、Rust的包管理工具Cargo
 - 四、项目结构
 - 1.Cargo.toml文件
 - 2.创建一个可执行文件项目
 - 3.创建一个库项目
 
- 参考
 
一、Rust的编译器rustc
·查看版本
rustc-version
 
·编译生成二进制文件
rustc -o output filename filename.rs
 
·编译生成库文件
rustc --crate-type lib filename.rs
 
fn main()
{println!("Hello, world!");
}
 
编译及运行
▶ rustc main.rs -o main
▶ ./main 
Hello, world!
 
二、开发环境搭建
vscode
- rust-analyzer
 - Error Lens(错误提示)
 
运行以下命令去安装 Rust-Analyzer:
Nightly Toolchain
rustup component add rust-analyzer-preview
 
rustup 会将 rust-analyzer 安装到以下路径:
 which rust-analyzer 
/home/wangji/.cargo/bin/rust-analyzer
 
这样的好处是 rust-analyzer 会跟随rustup rustc 一起更新,也能在不同 rustc 版本的项目中用相应版本的rust-analyzer.
配置在vscode中
 

参考:
- VS Code 配置 Rust-Analyzer
 
三、Rust的包管理工具Cargo
方式1:
 隐式地使用rustc进行编译
方式2:
・创建
cargo new project name
cargo new --lib project name创建一个新的Rust库项目的
 
构建项目(生成二进制可执行文件或库文件)
cargo build
cargo build-release为生成优化的可执行文件,常用于生产环境
 
检测
- 检测项目是否有错误
 
cargo check
 
·运行/测试
会运行两步
- cargo run实际是先执行cargo build,再执行二进制文件
 - cargo test是库项目的执行命令
 
cargo runcargo test
 
四、项目结构
库项目
project name/
----Cargo.toml
----src/-----lib.rs
 
二进制项目
project name/
----Cargo.toml
----src/------main.rs
 
1.Cargo.toml文件
package
- 设置项目名
 - 版本等
 
dependencies
- 设置依赖
 - [build-dependencies]列出了在构建项目时需要的依赖项(一般是适配环境,比如cargo build适配这个环境)
 - [dev-dependencies]列出了只在开发时需要的依赖项(一般是测试需要加载的依赖项)
 

2.创建一个可执行文件项目
cargo run等价于cargo build+执行二进制文件
cargo new project
▶ cargo runCompiling project v0.1.0 (/home/wangji/code/rust/project)Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.71sRunning `target/debug/project`
Hello, world!
 

cargo build --release优化后的二进制文件
▶ cargo build --releaseCompiling project v0.1.0 (/home/wangji/code/rust/project)Finished `release` profile [optimized] target(s) in 0.10s
 
cargo check检查项目的配置是否有问题
▶ cargo checkChecking project v0.1.0 (/home/wangji/code/rust/project)Finished `dev` profile [unoptimized + debuginfo] target(s) in 8.21s
 
3.创建一个库项目
▶ cargo new --lib project_libCreating library `project_lib` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
➜ project ⚡( master)                                                                                                   
 

运行cargo test
▶ cargo testCompiling project_lib v0.1.0 (/home/wangji/code/rust/project_lib)Finished `test` profile [unoptimized + debuginfo] target(s) in 7.44sRunning unittests src/lib.rs (target/debug/deps/project_lib-931d5b2ee036b7d3)running 1 test
test tests::it_works ... oktest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00sDoc-tests project_librunning 0 teststest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s➜ project_lib ⚡( master)                                     
 
参考
- 2024 Rust现代实用教程
 
