Rust学习第四天

本文介绍了Rust编程语言中的模块管理,包括`as`关键字、`use`导入以及如何将模块内容移动到其他文件。还详细讲解了字符串的使用,如`String`类型和`str`类型的区别,以及如何添加、访问和遍历元素。此外,还深入探讨了`HashMap`的数据结构,包括创建、访问和更新键值对的方法。最后,文章强调了Rust字符串的安全性和Hash函数的选择,指出Rust学习虽难但值得投入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • as关键字可以引入的路径指定本地的别名(和python一样)
  • 直接使用use导入路径是私有的
  • pub use :重导出
  • 使用外部包:Cargo.toml添加依赖项
  • use引入多个包,可以使用通配符*将包都引用出来:
use std::{
    collections::HashMap, 
    io
};


use std::io::{self, Write};
  •  将模块内容移到其他文件时:
  1. 模块定义时,如果模块名后边是“;”,而不是代码块:则Rust会从与模块同名的文件中加载内容,模块树的结构不会发生变化。
  2. 随着模块逐渐变大,该技术让你可以把模块的内容移到其他文件中。

  • 常用的集合

  • 向vector添加元素使用push
  • 删除vector:离开作用域
  • 读取vector:要么使用索引,要么使用get
fn main() {
    let mut v = vec![1, 2, 3];

    v.push(4);

    // println!("{:?}", v);

    let third: &i32 = &v[2];
    println!("The third element is {}.", third);

    match v.get(2) {
        Some(third) => println!("The third element is {}.", third),
        // 处理访问越界
        None => println!("There is no third element."),
    }
}
  •  遍历vector值用for循环
  • 使用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),
    ];
}
  • Rust字符串使用utf-8,Byte集合。
  • Rust的核心语言层面,只有一个字符串类型:字符串切片str(或&str)
  • String类型:
  1. 来自标准库,而不是核心语言
  2. 可增长、可修改、可拥有
  3. UTF-8编码
  • push_str()方法:把一个字符串切片附加到string(例子)
  • push()方法:把单个字符附加到String
  • +:连接字符串
  • format!拼接字符串
fn main() {
    let s1 = String::from("tic");
    let s2 = String::from("tac");
    let s3 = String::from("toe");

    // let s3 = s1 + "-" + &s2 + "-" + &s3;
    // println!("{}", s3);

    let s = format!("{}-{}-{}", s1, s2, s3);
    println!("{}", s);
}
  • Rust字符串不支持语法访问
  • String类型是对Vector<u8>的包装 
  • Unicode变量值,所以Rust放弃字符串索引
  • 如果切割字符串时跨越了边界,就会导致恐慌
  • Hashmap是以键值对的形式存储数据
use std::collections::HashMap;

fn main() {
    // let mut scores: HashMap<String, i32> = HashMap::new();
    let mut scores = HashMap::new();

    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 15);
}
  • HashMap:
  1. HashMap用的较少,不在Prelude中
  2. 标准库对其支持较少,没有内置的宏来创建HashMap
  3. 数据存储在heap上
  4. 同构的。一个HashMap中:
    1. 所有的K必须是同一种类型
    2. 所有的V必须是同一种类型 
  •  另一种创建HashMap的方式:collect方法
use std::collections::HashMap;

fn main() {
    let teams = 
        vec![String::from("Blue"), String::from("Yellow")];
    let intial_scores = vec![10, 15];

    let scores: HashMap<_, _> = 
        teams.iter().zip(intial_scores.iter()).collect();
    println!("{:?}", scores);
}
  • 访问HashMap中的值使用get方法:参数:K,返回:OPtion<&V>
use std::collections::HashMap;

fn main() {
    let teams = 
        vec![String::from("Blue"), String::from("Yellow")];
    let intial_scores = vec![10, 15];

    let scores: HashMap<_, _> = 
        teams.iter().zip(intial_scores.iter()).collect();
    // println!("{:?}", scores);

    let team_name = String::from("Blue");
    let score = scores.get(&team_name);

    match score {
        Some(s) => println!("{}", s),
        None => println!("team not exist"),
    }
}
  • 遍历HashMap用for循环
  • 更新HashMap
  1. entry方法:Entry的or_insert()方法——检查指定的K是否存在V
use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();

    scores.insert(String::from("Blue"), 10);
    // 替换现有的值
    let e = scores.entry(String::from("Yellow"));
    println!("{:?}", e);
    e.or_insert(50);
    scores.entry(String::from("Blue")).or_insert(50);

    println!("{:?}", scores);
}
  • for循环遍历(统计词频):
use std::collections::HashMap;

fn main() {
    let text = "hello world wonderful world";

    let mut map = HashMap::new();

    for word in text.split_whitespace() {
        let count = map.entry(word).or_insert(0);
        *count += 1;
    }

    println!("{:#?}", map);
}
  • Hash函数:可以抵抗拒绝服务(DoS)攻击。不是可用的最快的Hash算法,但具有更好地安全性。 

总结

Rust真的很难学,但我是真的很想学会。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值