牛刀小试
1.Hello World
前面已经学习了Rust的一些基本知识和语法,现在我们从一个 Hello World 程序开始,编写Rust程序。
利用Cargo
新建项目:
// 在Windows IDE终端或者linux命令行中输入:
cargo new hello_world
在生成的项目中包含以下文件:
$ tree hello_world
hello_world
├── Cargo.toml
└── src
└── main.rs
cargo new hello_world
命令在当前目录下,为 Hello world
项目创建了一个同名的文件夹。 项目目录内初始包含了一个 Cargo.toml
文件,用于项目的配置与依赖管理,和一个源码文件夹 src
,其中包含了一个初始的 main.rs
源码文件,并实现了简单的语句打印功能。
运行命令:
cd ./hello_world
cargo run hello_world
运行结果:
Compiling hello_world v0.1.0 (/root/data/liziqiang/hello_world)
Finished dev [unoptimized + debuginfo] target(s) in 0.72s
Running `target/debug/hello_world`
Hello, world!
恭喜你!安装和前期的开发环境已经准备完毕。
main.rs
文件中就是rust
的程序。配置文件Cargo.toml
记录了这个包的版本、作者、仓库地址、描述、licence等信息;还包括依赖项、target设置、feature、patch等信息。
~/hello_world/Cargo.toml
:
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
[dependencies]
第一行,[package]
,是一个片段(section)标题,描述这个包的一些信息。随着我们在这个文件增加更多的信息,还将增加其他片段(section)。
[dependencies]
,是罗列项目依赖的片段的开始。在 Rust 中,代码包被称为 crate。这个项目并不需要其他的 crate。后续如果有依赖可以添加,添加的格式为:
[dependencies]
rand = "0.8.5"
2.代码练习
1.变量初始化
Rust
// 修复下面代码的错误并尽可能少的修改
fn main() {
let x: i32; // 未初始化,但被使用
let y: i32; // 未初始化,也未被使用
println!("x is equal to {}", x);
}
2.基本类型
Rust
// 移除某个部分让代码工作
fn main() {
let x: i32 = 5;
let mut y: u32 = 5;
y = x;
let z = 10; // 这里 z 的类型是?
}
3.字符类型
Rust
// 修改2处 `assert_eq!` 让代码工作
use std::mem::size_of_val;
fn main() {
let c1 = 'a';
assert_eq!(size_of_val(&c1),1);
let c2 = '中';
assert_eq!(size_of_val(&c2),3);
println!("Success!")
}
4.语句和表达式
Rust
// 使程序正常执行
fn main() {
let s = sum(1 , 2);
assert_eq!(s, 3);
}
fn sum(x: i32, y: i32) -> i32 {
x + y;
}
5.所有权
示例一:
Rust
fn main() {
// 使用尽可能多的方法来通过编译
let x = String::from("hello, world");
let y = x;
println!("{},{}",x,y);
}
示例二:
Rust
// 不要修改 main 中的代码
fn main() {
let s1 = String::from("hello, world");
let s2 = take_ownership(s1);
println!("{}", s2);
}
// 只能修改下面的代码!
fn take_ownership(s: String) {
println!("{}", s);
}
6.借用
示例一:
Rust
// 移除代码某个部分,让它工作
// 你不能移除整行的代码!
fn main() {
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = &mut s;
println!("{}, {}", r1, r2);
}
示例二:
Rust
// 修复错误
fn main() {
let mut s = String::from("hello, ");
borrow_object(s)
}
fn borrow_object(s: &String) {}