初面网初面网

Vector

标准库提供,可存放多个类型相同的值,值在内存中连续存放

let v: Vec<i32> = Vec::new(); // Vec::new()创建空的Vec,但空的Vec无法被编译器推断类型

let mut v2 = vec![1,2,3];   // 有初始值时可以直接使用vec!宏创建。这能够被自动推断出类型

v2.push(4);

println!("{:?}", v2);

下面代码演示了在vector中存放enum

enum SpreadsheetCell{
  Int(i32),
  Float(f64),
  Text(String),
}

fn main(){
  let row = vec![
    SpreadsheetCell::Int(3),
    SpreadsheetCell::Text(String::from("blue")),
    SpreadsheetCell::Float(10.12),
  ]
}

String

字符串,是byte的集合,提供一些方法,将byte解析为文本。语言层面上指前面提到的字符串切片。

而String类型,来自标准库,可增长、可修改、可拥有。

// 很多Vec<T>操作都可用于String
let mut s = String::new();

let s1 = "hello world".to_string();   // 转换成String类
let s2 = String::from("Hello World!!");

向已有的字符串中添加

// 添加切片
let mut s = String::from("hello");
s.push_str(" world");

// 附加字符
s.push('!');
s.push('!');

format格式化输出

let s1 = String::from("hello");
let s2 = String::from(" world");
let s3 = String::from("!!!");

print!("{}", format!("{}{}{}", s1, s2, s3));

HashMap

键值对形式存储数据。

HashMap<K, V>

// hashmap用得较少,所以没有内置,必须引入
use std::collections::HashMap;

// 创建与添加
let mut scores = HashMap::new();  // 创建
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 26);

print!("{:?}", scores.get(&String::from("Blue")));  // Some(10);

/*
实际上hashmap的输出用match更方便
let score = scores.get(&String::from("Blue"));
match score{
  Some(s) => println!("{}", s),
  None => println!("Nothing to print!");
}

*/

更新hashmap

scores.entry(String::from("Blue")).or_insert(12);

下面是用vector和元组返回出HashMap的例子。仅作为了解

let teams = vec![String::from("Blud"), String::from("Yellow")];
let intial_scores = vec![10, 50];

let scores: HashMap<_, _> = teams.iter().zip(intial_scores.iter()).collect(); // 主要留意zip的用法

更新于 2026/3/1