Skip to content

Rust 集合与字符串

概述

Rust 标准库包含许多有用的集合类型。

📚 Vector

rust
fn main() {
    let mut v = Vec::new();
    v.push(5);
    v.push(6);
    v.push(7);
    v.push(8);
    
    let v = vec![1, 2, 3, 4, 5];
    let third: &i32 = &v[2];
    println!("The third element is {}", third);
}

📚 字符串

rust
fn main() {
    let mut s = String::new();
    let data = "initial contents";
    let s = data.to_string();
    let s = String::from("initial contents");
    
    let mut s = String::from("foo");
    s.push_str("bar");
    println!("{}", s);
}

📚 HashMap

rust
use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    
    let team_name = String::from("Blue");
    let score = scores.get(&team_name);
    println!("{:?}", score);
}

继续学习下一章 - Rust 面向对象

本站内容仅供学习和研究使用。