Package、Crate、Module、Path
, 2018 改过一次,第一次学习建议跳过.这点是 rust 和其他语言都不太相同的地方,记住以下几点:
let s1 = String::from("hello"); let s2 = s1;
这句话之后 s1 就失效了. Rust 永远也不会自动创建数据的 "深拷贝", 但是基本类型的组合会被自动拷贝,比如 let x = 5; let y = x
, x,y 都是有效的. 如下是一些 Copy 的类型:规则如下:
借用
和引用
的值即:在任意给定时间,要么 只能有一个可变引用,要么 只能有多个不可变引用。引用必须总是有效的。
if x {} else if y {} else {}
let a = if x {1} else {2}
loop
, while
, for
, 熟悉 go 语言的可能会感觉很多余,在 go 里面实际上一个 for 关键字可以表达所有情况了struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
fn build_user(email: String, username: String) -> User {
User {
email,
username,
active: true,
sign_in_count: 1,
}
}
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn area(rectangle: &Rectangle) -> u32 {
rectangle.width * rectangle.height
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
// impl 块的另一个有用的功能是:允许在 impl 块中定义 不 以 self 作为参数的函数。
// 这被称为 关联函数(associated functions)
}
# 使用 match 表达式
fn read_from_file() -> Result<String, io::Error>{
let f = File::open("hello.txt");
let mut f = match f {
Ok(file) => file,
Err(error) => return Err(e),
};
let mut s = String::new();
match f.read_to_string(&mut s) {
OK(_) => Ok(s),
Err(e) => Err(e),
}
}
# 使用 ? 表达式 + 链式表达式 (注意 ? 只用于返回为 Result 的函数内)
fn read_from_file() -> Result<String, io::Error>{
let mut s = String::new();
File::open("hello.txt")?.read_to_string(&mut s)?;
Ok(s)
}
let mut v1 = vec![];
let mut v2 = vec![0; 10];
let mut v3: Vec<i32> = Vec::new();
let mut hmap = HashMap::new();
hmap.insert(1, "a");
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
let mut largest = list[0];
for &item in list.iter() {
if item > largest {
largest = item;
}
}
largest
}
let number_list = vec![34, 50, 25, 100, 65];
let result = largest(&number_list);
println!("The largest number is {}", result);
生命周期和所有权一样,是 rust 中最特殊的概念
生命周期并不总是指明,省略规则如下【规则会变化,生命周期的规则在 rust 的进化过程会不断打补丁】:
// 周期 'a 实际生命周期是 x, y 中两个生命周期里面短的那个
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str{
if x.len() > y.len(){
x
}else{
y
}
}
|参数|{ 实现}
(不要求标注参数和返回值类型,使用编译器自动推断);使用的方法和 golang 大体相同,只有小部分区别:Rc::strong_count
; Rc::weak_count
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。