RustDay04------Exercise[21-30]
21.使用()对变量进行解包
// primitive_types5.rs
// Destructure the `cat` tuple so that the println will work.
// Execute `rustlings hint primitive_types5` or use the `hint` watch subcommand for a hint.fn main() {let cat = ("Furry McFurson", 3.5);// 这里要使用()解包 而不是{}解包let (name,age)= cat;println!("{} is {} years old.", name, age);
}
22.元组的下标引用
使用.index来进行下标索引,注意数组依旧采取[index]的方式来进行下标索引
// primitive_types6.rs
// Use a tuple index to access the second element of `numbers`.
// You can put the expression for the second element where ??? is so that the test passes.
// Execute `rustlings hint primitive_types6` or use the `hint` watch subcommand for a hint.#[test]
fn indexing_tuple() {let numbers = (1, 2, 3);// Replace below ??? with the tuple indexing syntax.let second = numbers.1;assert_eq!(2, second,"This is not the 2nd number in the tuple!")
}
23.使用Vec!来创建数组
注意是小写的vec!
// vecs1.rs
// Your task is to create a `Vec` which holds the exact same elements
// as in the array `a`.
// Make me compile and pass the test!
// Execute `rustlings hint vecs1` or use the `hint` watch subcommand for a hint.fn array_and_vec() -> ([i32; 4], Vec<i32>) {let a = [10, 20, 30, 40]; // a plain arraylet v = vec![10, 20, 30, 40];// TODO: declare your vector here with the macro for vectors(a, v)
}#[cfg(test)]
mod tests {use super::*;#[test]fn test_array_and_vec_similarity() {let (a, v) = array_and_vec();assert_eq!(a, v[..]);}
}
24.Vec和map的遍历迭代
// vecs2.rs
// A Vec of even numbers is given. Your task is to complete the loop
// so that each number in the Vec is multiplied by 2.
//
// Make me pass the test!
//
// Execute `rustlings hint vecs2` or use the `hint` watch subcommand for a hint.fn vec_loop(mut v: Vec<i32>) -> Vec<i32> {for i in v.iter_mut() {// TODO: Fill this up so that each element in the Vec `v` is// multiplied by 2.*i*=2;}// At this point, `v` should be equal to [4, 8, 12, 16, 20].v
}fn vec_map(v: &Vec<i32>) -> Vec<i32> {v.iter().map(|num| {// TODO: Do the same thing as above - but instead of mutating the// Vec, you can just return the new number!num*2}).collect()
}#[cfg(test)]
mod tests {use super::*;#[test]fn test_vec_loop() {let v: Vec<i32> = (1..).filter(|x| x % 2 == 0).take(5).collect();let ans = vec_loop(v.clone());assert_eq!(ans, v.iter().map(|x| x * 2).collect::<Vec<i32>>());}#[test]fn test_vec_map() {let v: Vec<i32> = (1..).filter(|x| x % 2 == 0).take(5).collect();let ans = vec_map(&v);assert_eq!(ans, v.iter().map(|x| x * 2).collect::<Vec<i32>>());}
}
25.可变借用
开始vec1没有生命mut 所以push会报错 ,加上mut申明即可
// move_semantics1.rs
// Execute `rustlings hint move_semantics1` or use the `hint` watch subcommand for a hint.// I AM NOT DONEfn main() {let vec0 = Vec::new();let mut vec1 = fill_vec(vec0);println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);vec1.push(88);println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}fn fill_vec(vec: Vec<i32>) -> Vec<i32> {let mut vec = vec;vec.push(22);vec.push(44);vec.push(66);vec
}
26.不能修改传入给函数的参数,但是可以修改其克隆体(应该是这样??)
Rust不允许在默认情况下修改传递给函数的参数,但当你明确地创建一个克隆(clone)时,你可以在函数内部对克隆进行修改,因为克隆是一个独立的拥有者。
// move_semantics2.rs
// Make me compile without changing line 13 or moving line 10!
// Execute `rustlings hint move_semantics2` or use the `hint` watch subcommand for a hint.// I AM NOT DONEfn main() {let vec0 = Vec::new();let mut vec1 = fill_vec(vec0.clone());// Do not change the following line!println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0);vec1.push(88);println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}fn fill_vec(vec: Vec<i32>) -> Vec<i32> {let mut vec = vec;vec.push(22);vec.push(44);vec.push(66);vec
}
27.全部变成mut,解决所有烦恼
// move_semantics3.rs
// Make me compile without adding new lines-- just changing existing lines!
// (no lines with multiple semicolons necessary!)
// Execute `rustlings hint move_semantics3` or use the `hint` watch subcommand for a hint.// I AM NOT DONEfn main() {let mut vec0 = Vec::new();let mut vec1 = fill_vec(&mut vec0);println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);vec1.push(88);println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}fn fill_vec(vec: &mut Vec<i32>) -> &mut Vec<i32> {vec.push(22);vec.push(44);vec.push(66);vec
}
28.不传入参数,在函数内部创建vector
这里是题目要求
// move_semantics4.rs
// Refactor this code so that instead of passing `vec0` into the `fill_vec` function,// the Vector gets created in the function itself and passed back to the main *******!!!// function.
// Execute `rustlings hint move_semantics4` or use the `hint` watch subcommand for a hint.// I AM NOT DONEfn main() {// let vec0 = Vec::new();let mut vec1 = fill_vec();println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);vec1.push(88);println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}// `fill_vec()` no longer takes `vec: Vec<i32>` as argument
fn fill_vec() -> Vec<i32> {// let mut vec = vec;let mut vec=Vec::new();vec.push(22);vec.push(44);vec.push(66);vec
}
29.不能同时存在多个可变引用
// move_semantics5.rs
// Make me compile only by reordering the lines in `main()`, but without
// adding, changing or removing any of them.
// Execute `rustlings hint move_semantics5` or use the `hint` watch subcommand for a hint.// 在任何给定时间,要么只能有一个可变引用,要么可以有多个不可变引用。// 不可变引用和可变引用之间是互斥的,不能同时存在。
fn main() {let mut x = 100;let y = &mut x;*y += 100;let z = &mut x;*z += 1000;assert_eq!(x, 1200);
}
30.传递引用,避免对非mut申明变量的引用,通过覆盖变量达到避免对原参数的修改
// move_semantics6.rs
// Execute `rustlings hint move_semantics6` or use the `hint` watch subcommand for a hint.
// You can't change anything except adding or removing references.// I AM NOT DONEfn main() {let data = "Rust is great!".to_string();get_char(&data);string_uppercase(&data);
}// Should not take ownership
// fn get_char(data: String) -> char 这样会获取所有权
fn get_char(data: &String) -> char {data.chars().last().unwrap()
}// Should take ownership
fn string_uppercase(mut data: &String) {let data = &data.to_uppercase();println!("{}", data);
}
相关文章:

RustDay04------Exercise[21-30]
21.使用()对变量进行解包 // primitive_types5.rs // Destructure the cat tuple so that the println will work. // Execute rustlings hint primitive_types5 or use the hint watch subcommand for a hint.fn main() {let cat ("Furry McFurson", 3.5);// 这里…...

OpenAI科学家谈GPT-4的潜力与挑战
OpenAI Research Scientist Hyung Won Chung 在首尔国立大学发表的一场演讲。 模型足够大,某些能力才会显现,GPT-4 即将超越拐点并在其能力上实现显着跳跃。GPT-3 和 GPT-4 之间的能力仍然存在显着差距,并且尝试弥合与当前模型的差距可能是无…...

Java电子病历编辑器项目源码 采用B/S(Browser/Server)架构
电子病历(EMR,Electronic Medical Record)是用电子技术保存、管理、传输和重现的数字化的病人的医疗记录,取代手写纸张病历,将医务人员在医疗活动过程中,使用医疗机构管理系统生成的文字、符号、图表、图形、数据、影像等数字化内…...

使用 AWS DataSync 进行跨区域 AWS EFS 数据传输
如何跨区域EFS到EFS数据传输 部署 DataSync 代理 在可以访问源 EFS 和目标 EFS 的源区域中部署代理。转至AWS 代理 AMI 列表并按 AWS 区域选择您的 AMI。对于 us-west-1,单击 us-west-1 前面的启动实例。 启动实例 2. 选择您的实例类型。AWS 建议使用以下实例类型之…...

设计模式~解释器模式(Interpreter)-19
解释器模式(Interpreter Pattern)提供了评估语言的语法或表达式的方式,它属于行为型模式。这种模式实现了一个表达式接口,该接口解释一个特定的上下文。这种模式被用在 SQL 解析、符号处理引擎等。 【俺有一个《泡MM真经》&#x…...

对象混入的实现方式
对象混入(Object mixins)是一种在面向对象编程中用于组合和重用代码的技术。它允许你将一个对象的属性和方法混合(或合并)到另一个对象中,从而创建一个具有多个来源的对象,这些来源可以是不同的类、原型或其…...

Mac 远程 Ubuntu
1. Iterm2 添加ssh 参考:https://www.javatang.com/archives/2021/11/29/13063392.html 2. Finder 添加远程文件管理 2.1 ubuntu 配置 安装samba sudo apt-get install samba配置 [share]path /home/USER_NAME/shared_directoryavailable yesbrowseable ye…...

黑豹程序员-h5前端录音、播放
H5支持页面中调用录音机进行录音 H5加入录音组件,录音后可以进行播放,并形成录音文件,其采样率固化48000,传言是google浏览器的BUG,它无法改动采样率。 大BUG,目前主流的支持16000hz的采样率。 录音组件 …...

Leetcode622.设计循环队列
本专栏内容为:leetcode刷题专栏,记录了leetcode热门题目以及重难点题目的详细记录 💓博主csdn个人主页:小小unicorn ⏩专栏分类:Leetcode 🚚代码仓库:小小unicorn的代码仓库🚚 &…...

二十二、【形状工具组】
文章目录 基础图形多边形直线工具自定义形状工具 形状工具组画的图形是矢量图形,在放大和缩小后像素不变看起来不会模糊,位图和矢量图形的存储方式不一样,位图的存储方式是按各个像素的数据来进行存储的,而矢量图形是根据算法来进…...

设计模式~迭代器模式(Iterator)-20
目录 迭代器模式(Iterator) (1)优点 (2)缺点 (3)使用场景 (4)注意事项 (5)应用实例: 代码 迭代器模式(Iterator) 迭代器模式(…...

亳州市的自然风光与旅游资源:欣赏安徽省中部的壮丽景色
亳州市是中国安徽省的一个地级市,位于该省的中部。 亳州市辖区包括谯城区、涡阳县、蒙城县和利辛县等地。亳州市拥有悠久的历史和丰富的文化遗产,同时也以其独特的自然风光而闻名。 首先,让我们来了解一下亳州的历史和景点。亳州的历史可以…...

windows安装nvm以及解决yarn问题
源代码 下载 下一步一下步安装即可 检查是否安装成功 nvm出现上面的代码即可安装成功 常用命令 查看目前安装的node版本 nvm list [available]说明没有安装任何版本,下面进行安装 nvm install 18.14使用该版本 node use 18.14.2打开一个新的cmd输入node -…...

【TA 挖坑04】薄膜干涉 镭射材质 matcap
镭射材质,相对物理的实现? 万物皆可镭射,个性吸睛的材质渲染技术 - 知乎 (zhihu.com) 薄膜干涉材质,matcap更trick的方法?matcapremap, MatCap原理介绍及应用 - 知乎 (zhihu.com) 庄懂的某节课也做了mat…...

OpenCV13-图像噪声:椒盐噪声和高斯噪声
OpenCV13-图像噪声:椒盐噪声和高斯噪声 1.噪声种类2.椒盐噪声3.高斯噪声 1.噪声种类 图像噪声是指图像中的随机或非随机的不希望的视觉扰动。它可以出现在数字图像中的各种形式,例如颗粒状噪声、条纹、斑点、模糊、失真等。图像噪声可能是由于图像采集过…...

天堂2服务器基本设置
[system] server_nameLocal Server ——〉服务器名称 server_rulesPvP http_host127.0.0.1 ——〉HTTP注册页面(需先搭建IIS服务器) http_port8080 rs_host127.0.0.1——〉填你IP rs_port3724 ws_host127.0.0.1 ——〉填你的IP就对啦 ws_port8085 wor…...

如何解决网站被攻击的问题
在当今数字化时代,网站攻击已经成为互联网上的一个常见问题。这些攻击可能会导致数据泄漏、服务中断和用户信息安全问题。然而,我们可以采取一些简单的措施来解决这些问题,以确保网站的安全性和可用性。 使用强密码和多因素认证 密码是保护网…...

python爬虫入门详细教程-采集云南招聘网数据保存为csv文件
python爬虫之User-Agent大全、随机获取User-Agent 网站地址数据提取技术介绍采集目标流程分析python代码实现 网站地址 https://www.ynzp.com/ 这个网址特别适合新手拿来练习,你采集多了还有个验证码页面,验证码是4位数字,很清晰,…...

1.13.C++项目:仿muduo库实现并发服务器之TcpServer模块的设计
文章目录 一、LoopThreadPool模块二、实现思想(一)管理(二)流程(三)功能设计 三、代码 一、LoopThreadPool模块 TcpServer模块: 对所有模块的整合,通过 tcpserver 模块实例化的对象&…...

Spring(17) AopContext.currentProxy() 类内方法调用切入
目录 一、简介二、代码示例2.1 接口类2.2 接口实现类2.3 AOP切面类2.4 启动类(测试)2.5 执行结果 一、简介 背景: 在之前 Spring 的 AOP 用法中,只有代理的类才会被切入。例如:我们在 Controller 层调用 Service 的方式…...

自己的类支持基于范围的for循环 (深入探索)
自己的类支持基于范围的for循环 (深入探索) 编译器实际运行伪代码为: auto && __range range_expression; auto __begin begin_expr; auto __end end_expr; for (; __begin ! __end; __begin) {range_declaration *__begin;loop_statement }观察伪代码࿰…...

Multi Scale Supervised 3D U-Net for Kidney and Tumor Segmentation
目录 摘要1 引言2 方法2.1 预处理和数据增强2.2 网络的体系结构2.3 训练过程2.4 推理与后处理 3 实验与结果4 结论与讨论 摘要 U-Net在各种医学图像分割挑战中取得了巨大成功。一些新的、带有花里胡哨功能的架构可能在某些数据集中在使用最佳超参数时取得成功,但它们…...

《操作系统真象还原》第一章 部署工作环境
ref:https://www.bilibili.com/video/BV1kg4y1V7TV/?spm_id_from333.999.0.0&vd_source3f7ae4b9d3a2d84bf24ff25f3294d107 https://www.bilibili.com/video/BV1SQ4y1A7ZE/?spm_id_from333.337.search-card.all.click&vd_source3f7ae4b9d3a2d84bf24ff25f32…...

SpringCloud-Config
一、介绍 (1)服务注册中心 (2)管理各个服务上的application.yml,支持动态修改,但不会影响客户端配置 (3)一般将application.yml文件放在git上,客户端通过http/https方式…...

劣币驱良币的 pacing 之殇
都说 pacing 好 burst 孬(参见:为啥 pacing),就像都知道金币好,掺铁金币孬一样。可现实中掺铁的金币流通性却更好,劣币驱良币。劣币流通性好在卖方希望收到别人的良币而储存,而自己作为买方只使用劣币。 burst 和 pac…...

Gin 中的 Session(会话控制)
Session 介绍 session和cookie实现的底层目标是一致的,但是从根本而言实现的方法是不同的; session 是另一种记录客户状态的机制, 不同的是 Cookie 保存在客户端浏览器中,而 session保存 在服务器上 ; Session 的工作流程 当客户端浏览器第一次访问服务器并发送请求时,服…...

ChatGPT AIGC 实现数据分析可视化三维空间展示效果
使用三维空间图展示数据有以下一些好处: 1可视化复杂性:三维图可以展示三个或更多的变量,一眼就能看出数据各维度之间的关系,使复杂数据的理解和分析变得更为直观。 2检测模式和趋势:通过三维图,用户可以…...

Stable Diffusion 动画animatediff-cli-prompt-travel
基于 sd-webui-animatediff 生成动画或者动态图的基础功能,animatediff-cli-prompt-travel突破了部分限制,能让视频生成的时间更长,并且能加入controlnet和提示词信息控制每个片段,并不像之前 sd-webui-animatediff 的一套关键词控制全部画面。 动图太大传不上来,凑合看每…...

fatal error C1083: 无法打开包括文件: “ta_libc.h”: No such file or directory
用python做交易数据分析时,可以用talib库计算各类指标,这个库通过以下命令安装: pip install TA-Lib -i https://pypi.tuna.tsinghua.edu.cn/simple windows安装时可能出现本文标题所示的错误,可按如下步骤解决: 1、去…...

c 语言基础题目:L1-034 点赞
微博上有个“点赞”功能,你可以为你喜欢的博文点个赞表示支持。每篇博文都有一些刻画其特性的标签,而你点赞的博文的类型,也间接刻画了你的特性。本题就要求你写个程序,通过统计一个人点赞的纪录,分析这个人的特性。 …...