基础类型
数组
- 数组创建与遍历
#[test]
fn test_array() {
let a = [1, 2, 3, 5, 6];
let mut sum = 0;
for i in a {
sum += i;
}
// for i in 0..a.len() {
// sum += a[i];
// }
assert_eq!(17, sum);
}
- 修改数组元素
#[test]
fn test_mod_array() {
let b = [2, 5, 6, 8];
let mut b = b;
// for i in 0..b.len() {
// if b[i] % 2 == 0 {
// b[i] *= 3;
// }
// }
for val in b.iter_mut() {
if *val % 2 == 0 {
*val *= 3;
}
}
print!("{:?}", b);
}
注意数组的可变性和可变迭代;数组在编译时必须是确定长度的,因此无法删除数组中的元素(考虑使用动态可变长数组Vector)。
- 数组切片
[T; n]描述了一个数组的类型,而[T]则是切片的类型,其长度无法在编译期得知,数组切片通常通过引用的方式去使用,因此其实际的类型是&[T]:
#[test]
fn test_array_slice() {
let c: [i32; 5] = [1, 2, 3, 4, 5];
let slice: &[i32] = &c[1..3];
assert_eq!(slice, &[2, 3]);
}
字符串
字符串的实际类型是String,字面量是切片,数据存储格式实际上是[ u8 ]
- 基本使用
#[test]
fn test_string_iter() {
let s = "China中文";// &str
for ch in s.chars() {
print!("{:?}", ch);
}
let s = s.to_string(); // &str -> String
// String -> Vec<char> -> Vec<u8>
let s_bytes = s.chars().map(|x| u8::try_from(x).unwrap()).collect::<Vec<u8>>();
assert_eq!(7, s_bytes.len());
}
- 字符串操作
#[test]
fn test_string_oper() {
let mut s = String::from("Are you"); //&str -> String
s.push_str(" OK");
assert_eq!("Are you OK", s);
s.push('?');
assert_eq!("Are you OK?", s);
s.insert(0, 'L');
s.insert_str(1, "Hou: ");
assert_eq!("LHou: Are you OK?", s);
}
删除操作:
枚举
Option
是一个枚举,属于标准库(Rust没有null关键字,None表示成员没有值而不是指向一个空引用):
enum Option<T> {
Some(T),
None
}
-
API
- as_ref: Converts from
&Option<T>
toOption<&T>
- as_mut: Converts from
&mut Option<T>
toOption<&mut T>
- unwrap: Returns the contained
Some
value, consuming the self value.
Panics if the self value equals None. - map:
let maybe_some_string = Some(String::from("Hello, World!")); // `Option::map` takes self *by value*, consuming `maybe_some_string` let maybe_some_len = maybe_some_string.map(|s| s.len()); assert_eq!(maybe_some_len, Some(13)); let x: Option<&str> = None; assert_eq!(x.map(|s| s.len()), None);
- take: Takes the value out of the option, leaving a None in its place.
- as_ref: Converts from
集合
Vector
- 入栈、出栈:push/pop
- 迭代遍历:for in
- 排序
- 稳定排序:sort/sort_by
- 非稳定排序: sort_unstable/sort_unstable_by