当前位置: 首页 > news >正文

Rust4.2 Common Collections

Rust学习笔记

Rust编程语言入门教程课程笔记

参考教材: The Rust Programming Language (by Steve Klabnik and Carol Nichols, with contributions from the Rust Community)

Lecture 8: Common Collections

fn main() {//Vectorlet mut v: Vec<i32> = Vec::new();//new empty vectorv.push(1);let v2 = &v[0];//immutable borrow//v.push(2);//mutable borrow//cannot borrow `v` as mutable because it is also borrowed as immutable//because v.push will cause the vector to reallocate and invalidate the reference//so v2 may be pointing to deallocated memoryprintln!("The first element is: {}", v2);let mut u = vec![1, 2, 3];//new vector with valuesprintln!("u[0] = {:?}", u[0]);//access element with indexprintln!("u[1] = {:?}", u.get(1));//access element with get()match u.get(1) {Some(second) => println!("The second element is {}", second),None => println!("There is no second element."),}u.insert(0, 0);//insert element at indexfor i in &u {//immutable borrowprintln!("{}", i);}for i in &mut u {//mutable borrow*i += 50; //dereference i and add 50 to it}//using enum to store multiple types in a vectorenum SpreadsheetCell {Int(i32),Float(f64),Text(String),}let row = vec![SpreadsheetCell::Int(3),SpreadsheetCell::Float(10.12),SpreadsheetCell::Text(String::from("blue")),];for i in &row {//for + matchmatch i {SpreadsheetCell::Int(i) => println!("Int: {}", i),SpreadsheetCell::Float(f) => println!("Float: {}", f),SpreadsheetCell::Text(s) => println!("Text: {}", s),}}//Stringlet mut s = String::new();//new empty stringprintln!("{}", s);let data = "initial contents 0";//new string from string literals = data.to_string();//new string from string literalprintln!("{}", s);s = "initial contents 1".to_string();//new string from string literalprintln!("{}", s);s = String::from("initial contents 2");//new string from string literalprintln!("{}", s);s.push_str("bar");//append string literalprintln!("{}", s);s.push('l');//append charprintln!("{}", s);//concatenationlet s1 = String::from("Hello, ");let s2 = String::from("world!");let s3 = s1 + &s2;//s1 has been moved here and can no longer be usedprintln!("{}", s3);//format! macrolet s1 = String::from("tic");let s2 = String::from("tac");let s3 = String::from("toe");let s4 = format!("{}-{}-{}", s1, s2, s3);//s1, s2, s3 not movedprintln!("{}", s1);println!("{}", s2);println!("{}", s3);println!("{}", s4);//indexinglet s1 = String::from("hello");//let h = s1[0];//cannot index into a Stringlet h = &s1[0..1];//indexing with rangeprintln!("{}", h);//lengthlet len = String::from("Hola").len();//length in bytesprintln!("{}", len);let len = String::from("Здравствуйте").len();//length in bytesprintln!("{}", len);let len = String::from("Здравствуйте").chars().count();//length in charsprintln!("{}", len);//iterationfor c in "नमस्ते".chars() {println!("{}", c);}for b in "नमस्ते".bytes() {println!("{}", b);}//Hash Map//HashMap<K, V> stores a mapping of keys of type K to values of type Vuse std::collections::HashMap;//hashmap is not in the preludelet mut scores = HashMap::new();//new empty HashMapscores.insert(String::from("Blue"), 10);//insert key-value pairscores.insert(String::from("Yellow"), 50);//insert key-value pairprintln!("{:?}", scores);//collecting into a hashmaplet teams = vec![String::from("Blue"), String::from("Yellow")];//new vectorlet initial_scores = vec![10, 50];//new vectorlet scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect();//collect into hashmap//HashMap<_,_> type annotation is needed because collect can collect into many different data structures//zip() creates a vector of tuplesprintln!("{:?}", scores);//ownershiplet field_name = String::from("Favorite color");let field_value = String::from("Blue");let mut map = HashMap::new();//new empty hashmap//map.insert(field_name, field_value);//field_name and field_value are moved into map//println!("{}", field_name);//field_name and field_value are moved into mapmap.insert(&field_name, &field_value);//field_name and field_value are borrowedprintln!("{}", field_name);//field_name and field_value are borrowed//accessing values in a hashmaplet team_name = String::from("Blue");let score = scores.get(&team_name);//get() returns an Option<&V>match score {Some(s) => println!("{}", s),None => println!("No score"),}//iterating over a hashmapfor (key, value) in &scores {println!("{}: {}", key, value);}//updating a hashmap//overwriting a valuelet mut scores = HashMap::new();//new empty hashmapscores.insert(String::from("Blue"), 10);//insert key-value pairscores.insert(String::from("Blue"), 25);//overwrite valueprintln!("{:?}", scores);//only inserting a value if the key has no valuescores.entry(String::from("Yellow"));//insert key-value pair if key has no valuescores.entry(String::from("Yellow")).or_insert(50);//insert key-value pair if key has no valuescores.entry(String::from("Blue")).or_insert(50);//do not insert key-value pair if key has valueprintln!("{:?}", scores);//updating a value based on the old valuelet text = "hello world wonderful world";let mut map = HashMap::new();//new empty hashmapfor word in text.split_whitespace() {//split string into wordslet count = map.entry(word).or_insert(0);//insert key-value pair if key has no value*count += 1;//dereference count and increment it}println!("{:?}", map);}

相关文章:

  • P6入门:项目初始化5-项目支出计划Spending Plan
  • 【计算机网络】VRRP协议理论和配置
  • Scala爬虫实战:采集网易云音乐热门歌单数据
  • 探索STM32系列微控制器的特性和性能
  • 二、Linux用户管理
  • Collectors.groupingBy方法的使用
  • 注意力机制(Attention)、自注意力机制(Self Attention)和多头注意力(Multi-head Self Attention)机制详解
  • Web安全之PHP的伪协议漏洞利用,以及伪协议漏洞防护方法
  • 【算法】算法题-20231114
  • 20. 机器学习——PCA 与 LDA
  • 神经网络激活函数的使用
  • 友元的三种实现
  • c语言-assert(断言)的笔记
  • openssl+sha256开发实例(C++)
  • 【Shell脚本10】Shell 流程控制
  • php的引用
  • 《Javascript数据结构和算法》笔记-「字典和散列表」
  • 30秒的PHP代码片段(1)数组 - Array
  • CoolViewPager:即刻刷新,自定义边缘效果颜色,双向自动循环,内置垂直切换效果,想要的都在这里...
  • Druid 在有赞的实践
  • extract-text-webpack-plugin用法
  • Java面向对象及其三大特征
  • Linux gpio口使用方法
  • Linux编程学习笔记 | Linux IO学习[1] - 文件IO
  • Mybatis初体验
  • MYSQL 的 IF 函数
  • python docx文档转html页面
  • Sequelize 中文文档 v4 - Getting started - 入门
  • Vue源码解析(二)Vue的双向绑定讲解及实现
  • WebSocket使用
  • 从零到一:用Phaser.js写意地开发小游戏(Chapter 3 - 加载游戏资源)
  • 电商搜索引擎的架构设计和性能优化
  • 简单数学运算程序(不定期更新)
  • 讲清楚之javascript作用域
  • 如何胜任知名企业的商业数据分析师?
  • 如何抓住下一波零售风口?看RPA玩转零售自动化
  • 延迟脚本的方式
  • ​批处理文件中的errorlevel用法
  • !!java web学习笔记(一到五)
  • #快捷键# 大学四年我常用的软件快捷键大全,教你成为电脑高手!!
  • (4)事件处理——(2)在页面加载的时候执行任务(Performing tasks on page load)...
  • (c语言版)滑动窗口 给定一个字符串,只包含字母和数字,按要求找出字符串中的最长(连续)子串的长度
  • (Java数据结构)ArrayList
  • (libusb) usb口自动刷新
  • ***利用Ms05002溢出找“肉鸡
  • .Net 8.0 新的变化
  • .NET Core MongoDB数据仓储和工作单元模式封装
  • .NET Core 控制台程序读 appsettings.json 、注依赖、配日志、设 IOptions
  • .net安装_还在用第三方安装.NET?Win10自带.NET3.5安装
  • .pop ----remove 删除
  • @configuration注解_2w字长文给你讲透了配置类为什么要添加 @Configuration注解
  • @property python知乎_Python3基础之:property
  • [Asp.net mvc]国际化
  • [BUUCTF NewStarCTF 2023 公开赛道] week3 crypto/pwn
  • [CSAWQual 2019]Web_Unagi ---不会编程的崽