rust数据类型支持primitive和compound类型,见下图
primitive类型
#![feature(core_intrinsics)]
fn print_type_of(_: T) {
println!("{}", unsafe { std::intrinsics::type_name::() });
}
fn main() {
println!("Hello, world!");
let logical: bool = true;
print_type_of(logical);
let mut inferred_type = 12;
print_type_of(inferred_type);
inferred_type = 4294967296i64;
print_type_of(inferred_type);
let t = "a";
print_type_of(t);
let c = 'a';
print_type_of(c);
}
compound数据类型
#![feature(core_intrinsics)]
fn print_type_of(_: T) {
println!("{}", unsafe { std::intrinsics::type_name::() });
}
fn main() {
let v = [1,2,3];
print_type_of(v);
let q:[i64; 3] = [1, 2, 3];
print_type_of(q);
let x: (i32, f64, u8) = (500, 6.4, 1);
print_type_of(x);
println!("{}", x.0);
println!("{}", x.2);
let a = [3; 5];
print_type_of(a);
//单元结构体
struct Empty;
let e = Empty;
print_type_of(e);
// 元组结构体
struct TT(i32, i32, i32);
let col = TT(0, 2, 4);
print_type_of(col);
// 具名结构体
struct People {
name: &'static str,
qender: i32,
}
let pe = People{name:"tt", qender:3};
print_type_of(pe);
enum Number {
Zero,
One,
Two,
}
let n = Number::One;
print_type_of(n)
}
collections
参见https://doc.rust-lang.org/std/index.html#containers-and-collections,这里定义了collections的几个关键元素
The option
and result
modules define optional and error-handling types, Option
and Result
. The iter
module defines Rust’s iterator trait, Iterator
, which works with the for
loop to access collections.
其中有几个基本元素需要注意定义
pub enum Option {
None,
Some(T),
}
enum Result {
Ok(T),
Err(E),
}
// iterator有70个左右的定义
pub trait Iterator {
type Item;
Show 70 methods}
collections包括:
- Sequences: Vec, VecDeque, LinkedList
- Maps: HashMap, BTreeMap
- Sets: HashSet, BTreeSet
- Misc: BinaryHeap
列举几个例子
vec
参考 https://doc.rust-lang.org/std/vec/struct.Vec.html#
fn main() {
println!("Hello, world!");
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
println!("{}", vec.len());
let p = vec.pop();
if (p.is_some()) {
println!("{}", p.unwrap());
}
}
HashMap
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
for (key, val) in map.iter() {
println!("key: {} val: {}", key, val);
}
}
小结
rust的数据类型还是比较丰富,融合了面向对象、函数式各种语言范式的长处。