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语言程序 (一)创建项目 (二)新建文件 (三)…...

2025季度云服务器排行榜
在全球云服务器市场,各厂商的排名和地位并非一成不变,而是由其独特的优势、战略布局和市场适应性共同决定的。以下是根据2025年市场趋势,对主要云服务器厂商在排行榜中占据重要位置的原因和优势进行深度分析: 一、全球“三巨头”…...
Xen Server服务器释放磁盘空间
disk.sh #!/bin/bashcd /run/sr-mount/e54f0646-ae11-0457-b64f-eba4673b824c # 全部虚拟机物理磁盘文件存储 a$(ls -l | awk {print $NF} | cut -d. -f1) # 使用中的虚拟机物理磁盘文件 b$(xe vm-disk-list --multiple | grep uuid | awk {print $NF})printf "%s\n"…...

2025年渗透测试面试题总结-腾讯[实习]科恩实验室-安全工程师(题目+回答)
安全领域各种资源,学习文档,以及工具分享、前沿信息分享、POC、EXP分享。不定期分享各种好玩的项目及好用的工具,欢迎关注。 目录 腾讯[实习]科恩实验室-安全工程师 一、网络与协议 1. TCP三次握手 2. SYN扫描原理 3. HTTPS证书机制 二…...
嵌入式常见 CPU 架构
架构类型架构厂商芯片厂商典型芯片特点与应用场景PICRISC (8/16 位)MicrochipMicrochipPIC16F877A、PIC18F4550简化指令集,单周期执行;低功耗、CIP 独立外设;用于家电、小电机控制、安防面板等嵌入式场景8051CISC (8 位)Intel(原始…...
离线语音识别方案分析
随着人工智能技术的不断发展,语音识别技术也得到了广泛的应用,从智能家居到车载系统,语音识别正在改变我们与设备的交互方式。尤其是离线语音识别,由于其在没有网络连接的情况下仍然能提供稳定、准确的语音处理能力,广…...

Visual Studio Code 扩展
Visual Studio Code 扩展 change-case 大小写转换EmmyLua for VSCode 调试插件Bookmarks 书签 change-case 大小写转换 https://marketplace.visualstudio.com/items?itemNamewmaurer.change-case 选中单词后,命令 changeCase.commands 可预览转换效果 EmmyLua…...
在鸿蒙HarmonyOS 5中使用DevEco Studio实现指南针功能
指南针功能是许多位置服务应用的基础功能之一。下面我将详细介绍如何在HarmonyOS 5中使用DevEco Studio实现指南针功能。 1. 开发环境准备 确保已安装DevEco Studio 3.1或更高版本确保项目使用的是HarmonyOS 5.0 SDK在项目的module.json5中配置必要的权限 2. 权限配置 在mo…...

DAY 45 超大力王爱学Python
来自超大力王的友情提示:在用tensordoard的时候一定一定要用绝对位置,例如:tensorboard --logdir"D:\代码\archive (1)\runs\cifar10_mlp_experiment_2" 不然读取不了数据 知识点回顾: tensorboard的发展历史和原理tens…...

工厂方法模式和抽象工厂方法模式的battle
1.案例直接上手 在这个案例里面,我们会实现这个普通的工厂方法,并且对比这个普通工厂方法和我们直接创建对象的差别在哪里,为什么需要一个工厂: 下面的这个是我们的这个案例里面涉及到的接口和对应的实现类: 两个发…...
标注工具核心架构分析——主窗口的图像显示
🏗️ 标注工具核心架构分析 📋 系统概述 主要有两个核心类,采用经典的 Scene-View 架构模式: 🎯 核心类结构 1. AnnotationScene (QGraphicsScene子类) 主要负责标注场景的管理和交互 🔧 关键函数&…...