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语言程序 (一)创建项目 (二)新建文件 (三)…...
day52 ResNet18 CBAM
在深度学习的旅程中,我们不断探索如何提升模型的性能。今天,我将分享我在 ResNet18 模型中插入 CBAM(Convolutional Block Attention Module)模块,并采用分阶段微调策略的实践过程。通过这个过程,我不仅提升…...
新能源汽车智慧充电桩管理方案:新能源充电桩散热问题及消防安全监管方案
随着新能源汽车的快速普及,充电桩作为核心配套设施,其安全性与可靠性备受关注。然而,在高温、高负荷运行环境下,充电桩的散热问题与消防安全隐患日益凸显,成为制约行业发展的关键瓶颈。 如何通过智慧化管理手段优化散…...
什么?连接服务器也能可视化显示界面?:基于X11 Forwarding + CentOS + MobaXterm实战指南
文章目录 什么是X11?环境准备实战步骤1️⃣ 服务器端配置(CentOS)2️⃣ 客户端配置(MobaXterm)3️⃣ 验证X11 Forwarding4️⃣ 运行自定义GUI程序(Python示例)5️⃣ 成功效果操作。它基于 SQLAlchemy ORM 框架 和一个自定义的装饰器 with_session 实现数据库会话管理。 📘 一、整体功能概述 该模块…...
高防服务器价格高原因分析
高防服务器的价格较高,主要是由于其特殊的防御机制、硬件配置、运营维护等多方面的综合成本。以下从技术、资源和服务三个维度详细解析高防服务器昂贵的原因: 一、硬件与技术投入 大带宽需求 DDoS攻击通过占用大量带宽资源瘫痪目标服务器,因此…...
篇章一 论坛系统——前置知识
目录 1.软件开发 1.1 软件的生命周期 1.2 面向对象 1.3 CS、BS架构 1.CS架构编辑 2.BS架构 1.4 软件需求 1.需求分类 2.需求获取 1.5 需求分析 1. 工作内容 1.6 面向对象分析 1.OOA的任务 2.统一建模语言UML 3. 用例模型 3.1 用例图的元素 3.2 建立用例模型 …...
生产管理系统开发:专业软件开发公司的实践与思考
生产管理系统开发的关键点 在当前制造业智能化升级的转型背景下,生产管理系统开发正逐步成为企业优化生产流程的重要技术手段。不同行业、不同规模的企业在推进生产管理数字化转型过程中,面临的挑战存在显著差异。本文结合具体实践案例,分析…...
OpenHarmony标准系统-HDF框架之I2C驱动开发
文章目录 引言I2C基础知识概念和特性协议,四种信号组合 I2C调试手段硬件软件 HDF框架下的I2C设备驱动案例描述驱动Dispatch驱动读写 总结 引言 I2C基础知识 概念和特性 集成电路总线,由串网12C(1C、12C、Inter-Integrated Circuit BUS)行数据线SDA和串…...
C#学习12——预处理
一、预处理指令: 解释:是在编译前由预处理器执行的命令,用于控制编译过程。这些命令以 # 开头,每行只能有一个预处理指令,且不能包含在方法或类中。 个人理解:就是游戏里面的备战阶段(不同对局…...
