简介
使用动态语言如 Ruby、Python 或 JavaScript
不习惯分多个步骤来编译和运行程序的方式
Rust 是一门预编译(ahead-of-time compiled)语言
意味着可以编译一个程序,将编译后的可执行文件给别人
即使他们没有安装 Rust 也可以运行程序
如果为其他人提供 .rb、.py 或 .js 文件
那么对方也需要分别安装对应 Ruby、Python 或 JavaScript 的语言支持环境
但是在这些语言中,只需要一条命令来编译和运行程序。一切都是语言设计权衡的结果
安装和编译
// 下载和安装Rust的官方编译器和包管理器Cargo
curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
// metadata和工具链将会被安装到Rustup home 目录: /Users/hello/.rustup
// 注意:这里在 /Users/hello下运行该命令
// 可以通过RUSTUP_HOME环境变量来更改
// Cargo主目录位于: /Users/hello/.cargo
// 可以通过CARGO_HOME环境变量来更改
// cargo, rustc, rustup 和其他命令将会被添加到Cargo's bin directory
// 位于: /Users/hello/.cargo/bin
The Cargo home directory is located at:
// PATH环境变量下将会添加
// /Users/hello/.profile
// /Users/hello/.bash_profile
// /Users/hello/.zshenv
// 执行curl时,得到如下信心
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
// 选择一之后,最后弹出
stable-x86_64-apple-darwin installed - rustc 1.70.0 (90c541806 2023-05-31)
// 重启当前shell,重新加载PATH环境变量,这样可以包含Cargo的bin目录$HOME/.cargo/bin).
// To configure your current shell
// 执行 source "$HOME/.cargo/env"
// 当尝试编译 Rust 程序并收到提示链接器无法执行的错误时,意味着系统未安装链接器
// 需要手动安装一个链接器
// 这是 Rust 用来将其编译的输出关联到一个文件中的程序
// 一些常见的 Rust 包依赖于 C 代码,需要 C 编译器
// 如果遇到链接器错误,安装一个 C 编译器,C 编译器通常带有正确的链接器
// 在 macOS 上,可运行以下命令获得 C 编译器:
// $ xcode-select --install
文件名:main.rs
fn main() {
println!("Hello, world!");
}
// 编译
// 编译成功后,Rust 就会输出一个二进制可执行文件
$ rustc main.rs
// 运行
$ ./main
Hello, world!
包管理
Cargo 是 Rust 的构建系统和包管理器
使用 Cargo 来管理 Rust 项目,它可以处理很多任务,比如构建代码、下载依赖库,以及编译依赖库
// 判断cargo是否安装成功
cargo --version
cargo 1.70.0 (ec8a8a0ca 2023-04-25)
// cargo创建新项目
cargo new hello_cargo
Created binary (application) `hello_cargo` package
cd hello_cargo
tree
.
├── Cargo.toml
└── src
└── main.rs
// 同时创建了vcs :版本控制系统
hello_cargo % ls -a
. .git Cargo.toml
.. .gitignore src
// 构建
// 创建一个可执行文件 target/debug/hello_cargo
cargo build
Compiling hello_cargo v0.1.0 (/Users/hello/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 0.51s
// 执行可执行文件
./target/debug/hello_cargo
Hello, world!
// 构建并运行
// 在一个命令中同时编译代码并运行生成的可执行文件
cargo run
// 快速检查代码确保其可以编译,但并不产生可执行文件
// cargo check
发布构建
当项目最终准备好发布时,可以使用 cargo build --release 来优化编译项目
这会在 target/release 而不是 target/debug 下生成可执行文件
这些优化可以让 Rust 代码运行的更快,不过启用这些优化也需要消耗更长的编译时间
两种配置去区别:
一种是为了开发,需要经常快速重新构建
一种是为用户构建最终程序,它们不会经常重新构建,并且希望程序运行得越快越好
如果要对代码运行时间进行基准测试
请确保运行 cargo build --release 并使用 target/release 下的可执行文件进行测试
对于简单项目, Cargo 并不比 rustc 提供了更多的优势,不过随着开发的深入,终将证明其价值文章来源:https://www.toymoban.com/news/detail-533656.html
要在任何已存在的项目上构建时,可以使用下面命令通过 Git 检出代码,进入到该项目目录并构建:文章来源地址https://www.toymoban.com/news/detail-533656.html
$ git clone example.org/someproject
$ cd someproject
$ cargo build
到了这里,关于Rust入门学习的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!