RustDay06------Exercise[71-80]
71.box的使用
说实话这题没太看懂.敲了个模板跟着提示就过了
// box1.rs
//
// At compile time, Rust needs to know how much space a type takes up. This
// becomes problematic for recursive types, where a value can have as part of
// itself another value of the same type. To get around the issue, we can use a
// `Box` - a smart pointer used to store data on the heap, which also allows us
// to wrap a recursive type.
//
// The recursive type we're implementing in this exercise is the `cons list` - a
// data structure frequently found in functional programming languages. Each
// item in a cons list contains two elements: the value of the current item and
// the next item. The last item is a value called `Nil`.
//
// Step 1: use a `Box` in the enum definition to make the code compile
// Step 2: create both empty and non-empty cons lists by replacing `todo!()`
//
// Note: the tests should not be changed
//
// Execute `rustlings hint box1` or use the `hint` watch subcommand for a hint.// I AM NOT DONE#[derive(PartialEq, Debug)]
pub enum List {Cons(i32, Box<List>),Nil,
}fn main() {println!("This is an empty cons list: {:?}", create_empty_list());println!("This is a non-empty cons list: {:?}",create_non_empty_list());
}pub fn create_empty_list() -> List {// todo!()List::Nil
}pub fn create_non_empty_list() -> List {// todo!()List::Cons(1, Box::new(List::Nil))
}#[cfg(test)]
mod tests {use super::*;#[test]fn test_create_empty_list() {assert_eq!(List::Nil, create_empty_list())}#[test]fn test_create_non_empty_list() {assert_ne!(create_empty_list(), create_non_empty_list())}
}
72.神奇的实例计数器
// rc1.rs
//
// In this exercise, we want to express the concept of multiple owners via the
// Rc<T> type. This is a model of our solar system - there is a Sun type and
// multiple Planets. The Planets take ownership of the sun, indicating that they
// revolve around the sun.
//
// Make this code compile by using the proper Rc primitives to express that the
// sun has multiple owners.
//
// Execute `rustlings hint rc1` or use the `hint` watch subcommand for a hint.// I AM NOT DONEuse std::rc::Rc;#[derive(Debug)]
struct Sun {}#[derive(Debug)]
enum Planet {Mercury(Rc<Sun>),Venus(Rc<Sun>),Earth(Rc<Sun>),Mars(Rc<Sun>),Jupiter(Rc<Sun>),Saturn(Rc<Sun>),Uranus(Rc<Sun>),Neptune(Rc<Sun>),
}impl Planet {fn details(&self) {println!("Hi from {:?}!", self)}
}fn main() {let sun = Rc::new(Sun {});println!("reference count = {}", Rc::strong_count(&sun)); // 1 referencelet mercury = Planet::Mercury(Rc::clone(&sun));println!("reference count = {}", Rc::strong_count(&sun)); // 2 referencesmercury.details();let venus = Planet::Venus(Rc::clone(&sun));println!("reference count = {}", Rc::strong_count(&sun)); // 3 referencesvenus.details();let earth = Planet::Earth(Rc::clone(&sun));println!("reference count = {}", Rc::strong_count(&sun)); // 4 referencesearth.details();let mars = Planet::Mars(Rc::clone(&sun));println!("reference count = {}", Rc::strong_count(&sun)); // 5 referencesmars.details();let jupiter = Planet::Jupiter(Rc::clone(&sun));println!("reference count = {}", Rc::strong_count(&sun)); // 6 referencesjupiter.details();// 从这里开始混入了奇怪的东西// TODOlet saturn = Planet::Saturn(Rc::clone(&sun));// Planet::Saturn(Rc::new(Sun {}));println!("reference count = {}", Rc::strong_count(&sun)); // 7 referencessaturn.details();// TODOlet uranus = Planet::Uranus(Rc::clone(&sun));// (Rc::new(Sun {}));println!("reference count = {}", Rc::strong_count(&sun)); // 8 referencesuranus.details();// TODOlet neptune = Planet::Neptune(Rc::clone(&sun));// (Rc::new(Sun {}));println!("reference count = {}", Rc::strong_count(&sun)); // 9 referencesneptune.details();assert_eq!(Rc::strong_count(&sun), 9);// 从这里开始下降drop(neptune);println!("reference count = {}", Rc::strong_count(&sun)); // 8 referencesdrop(uranus);println!("reference count = {}", Rc::strong_count(&sun)); // 7 referencesdrop(saturn);println!("reference count = {}", Rc::strong_count(&sun)); // 6 referencesdrop(jupiter);println!("reference count = {}", Rc::strong_count(&sun)); // 5 referencesdrop(mars);println!("reference count = {}", Rc::strong_count(&sun)); // 4 references// TODOdrop(earth);println!("reference count = {}", Rc::strong_count(&sun)); // 3 references// TODOdrop(venus);println!("reference count = {}", Rc::strong_count(&sun)); // 2 references// TODOdrop(mercury);println!("reference count = {}", Rc::strong_count(&sun)); // 1 referenceassert_eq!(Rc::strong_count(&sun), 1);
}
73.使用Arc创建共享变量
// arc1.rs
//
// In this exercise, we are given a Vec of u32 called "numbers" with values
// ranging from 0 to 99 -- [ 0, 1, 2, ..., 98, 99 ] We would like to use this
// set of numbers within 8 different threads simultaneously. Each thread is
// going to get the sum of every eighth value, with an offset.
//
// The first thread (offset 0), will sum 0, 8, 16, ...
// The second thread (offset 1), will sum 1, 9, 17, ...
// The third thread (offset 2), will sum 2, 10, 18, ...
// ...
// The eighth thread (offset 7), will sum 7, 15, 23, ...
//
// Because we are using threads, our values need to be thread-safe. Therefore,
// we are using Arc. We need to make a change in each of the two TODOs.
//
// Make this code compile by filling in a value for `shared_numbers` where the
// first TODO comment is, and create an initial binding for `child_numbers`
// where the second TODO comment is. Try not to create any copies of the
// `numbers` Vec!
//
// Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint.// I AM NOT DONE#![forbid(unused_imports)] // Do not change this, (or the next) line.
use std::sync::Arc;
use std::thread;fn main() {let numbers: Vec<_> = (0..100u32).collect();let shared_numbers = Arc::new(numbers);// TODOlet mut joinhandles = Vec::new();for offset in 0..8 {let child_numbers = shared_numbers.clone();// TODOjoinhandles.push(thread::spawn(move || {let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum();println!("Sum of offset {} is {}", offset, sum);}));}for handle in joinhandles.into_iter() {handle.join().unwrap();}
}
74.使用cow检测变量的所有权是否发生移动
很抽象这个没看懂
// cow1.rs
//
// This exercise explores the Cow, or Clone-On-Write type. Cow is a
// clone-on-write smart pointer. It can enclose and provide immutable access to
// borrowed data, and clone the data lazily when mutation or ownership is
// required. The type is designed to work with general borrowed data via the
// Borrow trait.
//
// This exercise is meant to show you what to expect when passing data to Cow.
// Fix the unit tests by checking for Cow::Owned(_) and Cow::Borrowed(_) at the
// TODO markers.
//
// Execute `rustlings hint cow1` or use the `hint` watch subcommand for a hint.// I AM NOT DONEuse std::borrow::Cow;fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> {for i in 0..input.len() {let v = input[i];if v < 0 {// Clones into a vector if not already owned.input.to_mut()[i] = -v;}}input
}#[cfg(test)]
mod tests {use super::*;#[test]fn reference_mutation() -> Result<(), &'static str> {// Clone occurs because `input` needs to be mutated.let slice = [-1, 0, 1];let mut input = Cow::from(&slice[..]);match abs_all(&mut input) {Cow::Owned(_) => Ok(()),_ => Err("Expected owned value"),}}#[test]fn reference_no_mutation() -> Result<(), &'static str> {// No clone occurs because `input` doesn't need to be mutated.let slice = [0, 1, 2];let mut input = Cow::from(&slice[..]);match abs_all(&mut input) {// TODOCow::Borrowed(_) => Ok(()),_ => Err("Expected borrowed value"),}}#[test]fn owned_no_mutation() -> Result<(), &'static str> {// We can also pass `slice` without `&` so Cow owns it directly. In this// case no mutation occurs and thus also no clone, but the result is// still owned because it was never borrowed or mutated.let slice = vec![0, 1, 2];let mut input = Cow::from(slice);match abs_all(&mut input) {// TODOCow::Owned(_) => Ok(()),_ => Err("Expected owned value"),}}#[test]fn owned_mutation() -> Result<(), &'static str> {// Of course this is also the case if a mutation does occur. In this// case the call to `to_mut()` returns a reference to the same data as// before.let slice = vec![-1, 0, 1];let mut input = Cow::from(slice);match abs_all(&mut input) {// TODOCow::Owned(_) => Ok(()),_ => Err("Expected owned value"),}}
}
75.等待线程
使用join()方法即可
// threads1.rs
//
// This program spawns multiple threads that each run for at least 250ms, and
// each thread returns how much time they took to complete. The program should
// wait until all the spawned threads have finished and should collect their
// return values into a vector.
//
// Execute `rustlings hint threads1` or use the `hint` watch subcommand for a
// hint.// I AM DONEuse std::thread;
use std::time::{Duration, Instant};fn main() {let mut handles = vec![];for i in 0..10 {handles.push(thread::spawn(move || {let start = Instant::now();thread::sleep(Duration::from_millis(250));println!("thread {} is complete", i);start.elapsed().as_millis()}));}let mut results: Vec<u128> = vec![];for handle in handles {// TODO: a struct is returned from thread::spawn, can you use it?results.push(handle.join().unwrap())}if results.len() != 10 {panic!("Oh no! All the spawned threads did not finish!");}println!();for (i, result) in results.into_iter().enumerate() {println!("thread {} took {}ms", i, result);}
}
76.给共享变量加上互斥锁
// threads2.rs
//
// Building on the last exercise, we want all of the threads to complete their
// work but this time the spawned threads need to be in charge of updating a
// shared value: JobStatus.jobs_completed
//
// Execute `rustlings hint threads2` or use the `hint` watch subcommand for a
// hint.// I AM NOT DONEuse std::sync::Arc;
use std::sync::Mutex;
use std::thread;
use std::time::Duration;struct JobStatus {jobs_completed: u32,
}fn main() {let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));let mut handles = vec![];for _ in 0..10 {let status_shared = Arc::clone(&status);let handle = thread::spawn(move || {thread::sleep(Duration::from_millis(250));// TODO: You must take an action before you update a shared valuestatus_shared.lock().unwrap().jobs_completed += 1;});handles.push(handle);}for handle in handles {handle.join().unwrap();// TODO: Print the value of the JobStatus.jobs_completed. Did you notice// anything interesting in the output? Do you have to 'join' on all the// handles?// println!("jobs completed {}", ???);}
}
77.要开起多个线程,需要使用不同的实例?
// threads3.rs
//
// Execute `rustlings hint threads3` or use the `hint` watch subcommand for a
// hint.// I AM NOT DONEuse std::sync::mpsc;
use std::sync::Arc;
use std::thread;
use std::time::Duration;struct Queue {length: u32,first_half: Vec<u32>,second_half: Vec<u32>,
}impl Queue {fn new() -> Self {Queue {length: 10,first_half: vec![1, 2, 3, 4, 5],second_half: vec![6, 7, 8, 9, 10],}}
}fn send_tx(q: Queue, tx: mpsc::Sender<u32>) -> () {let qc = Arc::new(q);let qc1 = Arc::clone(&qc);let qc2 = Arc::clone(&qc);let tx1 = tx.clone();let tx2 = tx.clone();thread::spawn(move || {for val in &qc1.first_half {println!("sending {:?}", val);tx1.send(*val).unwrap();thread::sleep(Duration::from_secs(1));}});thread::spawn(move || {for val in &qc2.second_half {println!("sending {:?}", val);tx2.send(*val).unwrap();thread::sleep(Duration::from_secs(1));}});
}fn main() {let (tx, rx) = mpsc::channel();let queue = Queue::new();let queue_length = queue.length;send_tx(queue, tx);let mut total_received: u32 = 0;for received in rx {println!("Got: {}", received);total_received += 1;}println!("total numbers received: {}", total_received);assert_eq!(total_received, queue_length)
}
78.宏函数的调用
需要加上!
// macros1.rs
//
// Execute `rustlings hint macros1` or use the `hint` watch subcommand for a
// hint.// I AM NOT DONEmacro_rules! my_macro {() => {println!("Check out my macro!");};
}fn main() {my_macro!();
}
79.宏需要在调用前声明,而不是调用后
// macros2.rs
//
// Execute `rustlings hint macros2` or use the `hint` watch subcommand for a
// hint.// I AM DONE
macro_rules! my_macro {() => {println!("Check out my macro!");};
}
fn main() {my_macro!();
}//old my_macro place
80.使用#[macro_use]属性暴露mod里面的宏函数
// macros3.rs
//
// Make me compile, without taking the macro out of the module!
//
// Execute `rustlings hint macros3` or use the `hint` watch subcommand for a
// hint.// I AM NOT DONE
#[macro_use]
mod macros {macro_rules! my_macro {() => {println!("Check out my macro!");};}
}fn main() {my_macro!();
}
相关文章:
RustDay06------Exercise[71-80]
71.box的使用 说实话这题没太看懂.敲了个模板跟着提示就过了 // box1.rs // // At compile time, Rust needs to know how much space a type takes up. This // becomes problematic for recursive types, where a value can have as part of // itself another value of th…...

Leetcode—2525.根据规则将箱子分类【简单】
2023每日刷题(五) Leetcode—2525.根据规则将箱子分类 实现代码 char * categorizeBox(int length, int width, int height, int mass){long long volume;long long len (long long)length;long long wid (long long)width;long long heig (long lo…...
RustDay05------Exercise[51-60]
51.使用?当作错误处理符 ? 是 Rust 中的错误处理操作符。通常用于尝试解析或执行可能失败的操作,并在出现错误时提前返回错误,以避免程序崩溃或出现未处理的错误。 具体来说,? 用于处理 Result 或 Option 类型的返回值。 // errors2.rs…...

hdlbits系列verilog解答(或非门)-07
文章目录 wire线网类型介绍一、问题描述二、verilog源码三、仿真结果 wire线网类型介绍 wire线网类型是verilog的一种数据类型,它是一种单向的物理连线。它可以是输入也可以是输出,它与reg寄存器数据类型不同,它不能存储数据,只能…...

Node学习笔记之path模块
path 模块提供了 操作路径 的功能,我们将介绍如下几个较为常用的几个 API: API 说明 path.resolve 拼接规范的绝对路径常用 path.sep 获取操作系统的路径分隔符 path.parse 解析路径并返回对象 path.basename 获取路径的基础名称 path.dirname…...
使用LangChain与chatGPT API开发故事推理游戏-海龟汤
项目概述 海龟汤简述: 主持人提出一个难以理解的事件,玩家通过提问来逐步还原事件,主持人仅能告知玩家:“是、不是、是也不是、不重要”。引入chatGPT API原因 想通过程序自动化主持人,可通过chatGPT来判断玩家推理正确与否。LangChain是什么 LangChain是一个强大的框架,…...

用ChatGPT编写Excel函数公式进行表格数据处理分析,so easy!
在用Excel进行数据处理分析时,经常需要编写不同的公式,需要了解大量的函数。有了ChatGPT,就很简单了,直接用自然语言描述自己的需求,然后让ChatGPT写出公式就好了。 例子1: Excel某个单元格的内容是&#…...

超全全国所有城市人力资本测算数据集(1990-2021年)
参考《管理世界》中詹新宇(2020)的做法,本文对地级市的人力资本水平进行测算,其中人力资本水平用地级市的普通高等学校在校学生数占该地区总人口比重来反映 一、数据介绍 数据名称:地级市-人力资本测算 数据年份&…...

(二)docker:建立oracle数据库mount startup
这章其实我想试一下startup部分做mount,因为前一章在建完数据库容器后,需要手动创建用户,授权,建表等,好像正好这部分可以放到startup里,在创建容器时直接做好;因为setup部分我实在没想出来能做…...

Hash Join(PostgreSQL 14 Internals翻译版)
一阶段哈希连接(One-Pass Hash Joins) 散列连接使用预构建的散列表搜索匹配的行。下面是一个使用这种连接的计划的例子: 在第一阶段,哈希连接节点1调用哈希节点2,哈希节点2从其子节点提取整个内部行集,并将…...

《SQLi-Labs》04. Less 23~28a
title: 《SQLi-Labs》04. Less 23~28a date: 2023-10-19 19:37:40 updated: 2023-10-19 19:38:40 categories: WriteUp:Security-Lab excerpt: 联合注入,注释符过滤绕过之构造闭合,%00 截断、二次注入、报错注入,空格过滤绕过&…...

文件打包下载excel导出和word导出
0.文件下载接口 请求 GET /pm/prj/menu/whsj/download/{affixId} 文件affixId多个id以逗号隔开。多个文件会以打包得形式。 1.Excel导出 1.0接口 POST 127.0.0.1:8400/pm/io/exportExcel/year-plan-table-workflow/report 参数 [{"org":"011","re…...

模拟退火算法求解TSP问题(python)
模拟退火算法求解TSP的步骤参考书籍《Matlab智能算法30个案例分析》。 问题描述 TSP问题描述在该书籍的第4章 算法流程 部分实现代码片段 坐标轴转换成两点之间直线距离长度的代码 coordinates np.array([(16.47, 96.10),(16.47, 94.44),(20.09, 92.54),(22.39, 93.37),(2…...

电路基础元件
文章目录 每周电子w5——电路元件基本电路元件电阻元件电容元件电感元件 每周电子w5——电路元件 基本电路元件 电路元件:是电路中最基本的组成单元 电路元件通过其端子与外部相连接;元件的特性则通过与端子有关的物理量描述每一种元件反映某种确定的电…...

百度地图API:JavaScript开源库几何运算判断点是否在多边形内(电子围栏)
百度地图JavaScript开源库,是一套基于百度地图API二次开发的开源的代码库。目前提供多个lib库,帮助开发者快速实现在地图上添加Marker、自定义信息窗口、标注相关开发、区域限制设置、几何运算、实时交通、检索与公交驾车查询、鼠标绘制工具等功能。 判…...

BFS专题8 中国象棋-马-无障碍
题目: 样例: 输入 3 3 2 1 输出 3 2 1 0 -1 4 3 2 1 思路: 单纯的BFS走一遍即可,只是方向坐标的移动变化,需要变化一下。 代码详解如下: #include <iostream> #include <vector> #include…...

R语言中fread怎么使用?
R语言中 fread 怎么用? 今天分享的笔记内容是数据读取神器fread,速度嘎嘎快。在R语言中,fread函数是data.table包中的一个功能强大的数据读取函数,可以用于快速读取大型数据文件,它比基本的read.table和read.csv函数更…...

element-plus 表格-自定义样式实现2
<template><h2>表格修改样式利用属性修改</h2><h3>row-style 行样式</h3><h3>row-style header-row-style 不能改背景色</h3><h3>cell-style header-cell-style能改背景色</h3><el-tableref"tableRef":dat…...

Mysql中的RR 隔离级别,到底有没有解决幻读问题
Mysql 中的 RR 事务隔离级别,在特定的情况下会出现幻读的问题。所谓的幻读,表示在同一个事务中的两次相同条件的查询得到的数据条数不一样。 在 RR 级别下,什么情况下会出现幻读 这样一种情况,在事务 1 里面通过 update 语句触发当…...

Visual Studio 2022下载安装的详细步骤-----C语言编辑器
目录 一、介绍 (一)和其他软件的区别 (二)介绍编写C语言的编辑器类型 二、下载安装 三、创建与运行第一个C语言程序 (一)创建项目 (二)新建文件 (三)…...

wordpress后台更新后 前端没变化的解决方法
使用siteground主机的wordpress网站,会出现更新了网站内容和修改了php模板文件、js文件、css文件、图片文件后,网站没有变化的情况。 不熟悉siteground主机的新手,遇到这个问题,就很抓狂,明明是哪都没操作错误&#x…...
变量 varablie 声明- Rust 变量 let mut 声明与 C/C++ 变量声明对比分析
一、变量声明设计:let 与 mut 的哲学解析 Rust 采用 let 声明变量并通过 mut 显式标记可变性,这种设计体现了语言的核心哲学。以下是深度解析: 1.1 设计理念剖析 安全优先原则:默认不可变强制开发者明确声明意图 let x 5; …...

idea大量爆红问题解决
问题描述 在学习和工作中,idea是程序员不可缺少的一个工具,但是突然在有些时候就会出现大量爆红的问题,发现无法跳转,无论是关机重启或者是替换root都无法解决 就是如上所展示的问题,但是程序依然可以启动。 问题解决…...

大数据学习栈记——Neo4j的安装与使用
本文介绍图数据库Neofj的安装与使用,操作系统:Ubuntu24.04,Neofj版本:2025.04.0。 Apt安装 Neofj可以进行官网安装:Neo4j Deployment Center - Graph Database & Analytics 我这里安装是添加软件源的方法 最新版…...

调用支付宝接口响应40004 SYSTEM_ERROR问题排查
在对接支付宝API的时候,遇到了一些问题,记录一下排查过程。 Body:{"datadigital_fincloud_generalsaas_face_certify_initialize_response":{"msg":"Business Failed","code":"40004","sub_msg…...
脑机新手指南(八):OpenBCI_GUI:从环境搭建到数据可视化(下)
一、数据处理与分析实战 (一)实时滤波与参数调整 基础滤波操作 60Hz 工频滤波:勾选界面右侧 “60Hz” 复选框,可有效抑制电网干扰(适用于北美地区,欧洲用户可调整为 50Hz)。 平滑处理&…...

遍历 Map 类型集合的方法汇总
1 方法一 先用方法 keySet() 获取集合中的所有键。再通过 gey(key) 方法用对应键获取值 import java.util.HashMap; import java.util.Set;public class Test {public static void main(String[] args) {HashMap hashMap new HashMap();hashMap.put("语文",99);has…...

基于Flask实现的医疗保险欺诈识别监测模型
基于Flask实现的医疗保险欺诈识别监测模型 项目截图 项目简介 社会医疗保险是国家通过立法形式强制实施,由雇主和个人按一定比例缴纳保险费,建立社会医疗保险基金,支付雇员医疗费用的一种医疗保险制度, 它是促进社会文明和进步的…...

使用分级同态加密防御梯度泄漏
抽象 联邦学习 (FL) 支持跨分布式客户端进行协作模型训练,而无需共享原始数据,这使其成为在互联和自动驾驶汽车 (CAV) 等领域保护隐私的机器学习的一种很有前途的方法。然而,最近的研究表明&…...

BCS 2025|百度副总裁陈洋:智能体在安全领域的应用实践
6月5日,2025全球数字经济大会数字安全主论坛暨北京网络安全大会在国家会议中心隆重开幕。百度副总裁陈洋受邀出席,并作《智能体在安全领域的应用实践》主题演讲,分享了在智能体在安全领域的突破性实践。他指出,百度通过将安全能力…...