RustDay05------Exercise[41-50]
41.使用模块的函数
mod
是用于创建模块的关键字。模块是一种组织代码的方式,它可以包含函数 (fn
)、结构体 (struct
)、枚举 (enum
)、常量 (const
)、其他模块 (mod
) 等。- 模块用于组织和封装代码,帮助将代码分割成可管理的单元。模块可以形成层次结构,允许你更好地组织和管理代码。
模块的函数一般是私有的,需要使用pub关键词将其暴露
// modules1.rs
// Execute `rustlings hint modules1` or use the `hint` watch subcommand for a hint.// I AM NOT DONEmod sausage_factory {// Don't let anybody outside of this module see this!fn get_secret_recipe() -> String {String::from("Ginger")}pub fn make_sausage() {get_secret_recipe();println!("sausage!");}
}fn main() {sausage_factory::make_sausage();
}
42.暴露读取私有方法的函数的属性的模板变量,以选择性地公布部分属性(设置为pub)
// modules2.rs
// You can bring module paths into scopes and provide new names for them with the
// 'use' and 'as' keywords. Fix these 'use' statements to make the code compile.
// Execute `rustlings hint modules2` or use the `hint` watch subcommand for a hint.// I AM NOT DONEmod delicious_snacks {// TODO: Fix these use statementspub use self::fruits::PEAR as fruit;pub use self::veggies::CUCUMBER as veggie;mod fruits {pub const PEAR: &'static str = "Pear";pub const APPLE: &'static str = "Apple";}mod veggies {pub const CUCUMBER: &'static str = "Cucumber";pub const CARROT: &'static str = "Carrot";}
}fn main() {println!("favorite snacks: {} and {}",delicious_snacks::fruit,delicious_snacks::veggie);
}
43.导入默认库的宏和库函数
// modules3.rs
// You can use the 'use' keyword to bring module paths from modules from anywhere
// and especially from the Rust standard library into your scope.
// Bring SystemTime and UNIX_EPOCH
// from the std::time module. Bonus style points if you can do it with one line!
// Execute `rustlings hint modules3` or use the `hint` watch subcommand for a hint.// I AM NOT DONE// TODO: Complete this use statement
use std::time::SystemTime;
use std::time::UNIX_EPOCH;fn main() {match SystemTime::now().duration_since(UNIX_EPOCH) {Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),Err(_) => panic!("SystemTime before UNIX EPOCH!"),}
}
44.new一个hashMap
HashMap::new()
注意末尾条件,添加足够种类和数量水果即可
// hashmaps1.rs
// A basket of fruits in the form of a hash map needs to be defined.
// The key represents the name of the fruit and the value represents
// how many of that particular fruit is in the basket. You have to put
// at least three different types of fruits (e.g apple, banana, mango)
// in the basket and the total count of all the fruits should be at
// least five.
//
// Make me compile and pass the tests!
//
// Execute `rustlings hint hashmaps1` or use the `hint` watch subcommand for a hint.// I AM NOT DONEuse std::collections::HashMap;fn fruit_basket() -> HashMap<String, u32> {let mut basket = HashMap::new();// TODO: declare your hash map here.// Two bananas are already given for you :)basket.insert(String::from("banana"), 2);// TODO: Put more fruits in your basket here.basket.insert("666".to_string(),3);basket.insert("999".to_string(),1);basket
}#[cfg(test)]
mod tests {use super::*;#[test]fn at_least_three_types_of_fruits() {let basket = fruit_basket();assert!(basket.len() >= 3);}#[test]fn at_least_five_fruits() {let basket = fruit_basket();assert!(basket.values().sum::<u32>() >= 5);}
}
45.hashmap的基础插入操作
注意末尾测试的要求即可
// hashmaps2.rs// A basket of fruits in the form of a hash map is given. The key
// represents the name of the fruit and the value represents how many
// of that particular fruit is in the basket. You have to put *MORE
// THAN 11* fruits in the basket. Three types of fruits - Apple (4),
// Mango (2) and Lychee (5) are already given in the basket. You are
// not allowed to insert any more of these fruits!
//
// Make me pass the tests!
//
// Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a hint.// I AM NOT DONEuse std::collections::HashMap;#[derive(Hash, PartialEq, Eq)]
enum Fruit {Apple,Banana,Mango,Lychee,Pineapple,
}fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {let fruit_kinds = vec![Fruit::Apple,Fruit::Banana,Fruit::Mango,Fruit::Lychee,Fruit::Pineapple,];for fruit in fruit_kinds {// TODO: Put new fruits if not already present. Note that you// are not allowed to put any type of fruit that's already// present!}
}#[cfg(test)]
mod tests {use super::*;fn get_fruit_basket() -> HashMap<Fruit, u32> {let mut basket = HashMap::<Fruit, u32>::new();basket.insert(Fruit::Apple, 4);basket.insert(Fruit::Mango, 2);basket.insert(Fruit::Lychee, 5);// at_least_five_types_of_fruits 种类>=5// greater_than_eleven_fruits 总数 >=1basket.insert(Fruit::Banana, 5);basket.insert(Fruit::Pineapple, 5);basket}#[test]fn test_given_fruits_are_not_modified() {let mut basket = get_fruit_basket();fruit_basket(&mut basket);assert_eq!(*basket.get(&Fruit::Apple).unwrap(), 4);assert_eq!(*basket.get(&Fruit::Mango).unwrap(), 2);assert_eq!(*basket.get(&Fruit::Lychee).unwrap(), 5);}#[test]fn at_least_five_types_of_fruits() {let mut basket = get_fruit_basket();fruit_basket(&mut basket);let count_fruit_kinds = basket.len();assert!(count_fruit_kinds >= 5);}#[test]fn greater_than_eleven_fruits() {let mut basket = get_fruit_basket();fruit_basket(&mut basket);let count = basket.values().sum::<u32>();assert!(count > 11);}
}
46.查看hashmap是否包含某个键
这一题有点综合性难度了,我们需要对每场比赛的双方统计得球和失球的次数,然后通过hashMap传递出去
// hashmaps3.rs// A list of scores (one per line) of a soccer match is given. Each line
// is of the form :
// <team_1_name>,<team_2_name>,<team_1_goals>,<team_2_goals>
// Example: England,France,4,2 (England scored 4 goals, France 2).// You have to build a scores table containing the name of the team, goals
// the team scored, and goals the team conceded. One approach to build
// the scores table is to use a Hashmap. The solution is partially
// written to use a Hashmap, complete it to pass the test.// Make me pass the tests!// Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a hint.// I AM NOT DONEuse std::collections::HashMap;// A structure to store team name and its goal details.
struct Team {name: String,goals_scored: u8,goals_conceded: u8,
}fn build_scores_table(results: String) -> HashMap<String, Team> {// The name of the team is the key and its associated struct is the value.let mut scores: HashMap<String, Team> = HashMap::new();for r in results.lines() {let v: Vec<&str> = r.split(',').collect();let team_1_name = v[0].to_string();let team_1_score: u8 = v[2].parse().unwrap();let team_2_name = v[1].to_string();let team_2_score: u8 = v[3].parse().unwrap();// TODO: Populate the scores table with details extracted from the// current line. Keep in mind that goals scored by team_1// will be number of goals conceded from team_2, and similarly// goals scored by team_2 will be the number of goals conceded by// team_1.if !scores.contains_key(&team_1_name) {// 创建新用户 都初始化为0scores.insert(team_1_name.clone(),Team{name: team_1_name.clone(),goals_scored: 0,goals_conceded: 0,});};if !scores.contains_key(&team_2_name) {// 创建新用户 都初始化为0scores.insert(team_2_name.clone(),Team{name: team_2_name.clone(),goals_scored: 0,goals_conceded: 0,});};let team1=scores.get_mut(&team_1_name).unwrap();team1.goals_scored+=team_1_score;team1.goals_conceded+=team_2_score;let team2=scores.get_mut(&team_2_name).unwrap();team2.goals_scored+=team_2_score;team2.goals_conceded+=team_1_score;}scores
}#[cfg(test)]
mod tests {use super::*;fn get_results() -> String {let results = "".to_string()+ "England,France,4,2\n"+ "France,Italy,3,1\n"+ "Poland,Spain,2,0\n"+ "Germany,England,2,1\n";results}#[test]fn build_scores() {let scores = build_scores_table(get_results());let mut keys: Vec<&String> = scores.keys().collect();keys.sort();assert_eq!(keys,vec!["England", "France", "Germany", "Italy", "Poland", "Spain"]);}#[test]fn validate_team_score_1() {let scores = build_scores_table(get_results());let team = scores.get("England").unwrap();assert_eq!(team.goals_scored, 5);assert_eq!(team.goals_conceded, 4);}#[test]fn validate_team_score_2() {let scores = build_scores_table(get_results());let team = scores.get("Spain").unwrap();assert_eq!(team.goals_scored, 0);assert_eq!(team.goals_conceded, 2);}
}
相关文章:
RustDay05------Exercise[41-50]
41.使用模块的函数 mod 是用于创建模块的关键字。模块是一种组织代码的方式,它可以包含函数 (fn)、结构体 (struct)、枚举 (enum)、常量 (const)、其他模块 (mod) 等。模块用于组织和封装代码,帮助将代码分割成可管理的单元。模块可以形成层次结构&…...

C语言实现通讯录(超详细)
1.实现怎样一个通讯录 实现一个通讯录联系人信息:1.可以保存100个人的信息名字2.添加联系人年龄3.删除指定联系人性别4.查找指定联系人电话5.修改指定联系人住址6.排序联系人7.显示所有联系人信息 2.通讯录的实现 2.1创建两个源文件和一个头文件 首先我们创建con…...
【Python机器学习】零基础掌握MinCovDet协方差估计
如何更精准地评估资产的风险和收益? 在投资领域,资产的风险和收益评估是至关重要的。传统的协方差矩阵虽然在某种程度上能反映资产间的关联性,但也存在一定的局限性。例如如果样本数量较少,传统的协方差矩阵可能会出现偏差,从而影响投资决策。 假设现在有一个投资组合,…...

2023年【四川省安全员A证】模拟试题及四川省安全员A证作业模拟考试
题库来源:安全生产模拟考试一点通公众号小程序 2023年四川省安全员A证模拟试题为正在备考四川省安全员A证操作证的学员准备的理论考试专题,每个月更新的四川省安全员A证作业模拟考试祝您顺利通过四川省安全员A证考试。 1、【多选题】36V照明适用的场所条…...
Flask项目log的集成
一、引入log 在项目的init.py文件中: import logging from logging.handlers import RotatingFileHandlerfrom flask_wtf.csrf import CSRFProtect from flask import Flask from flask_sqlalchemy import SQLAlchemy from redis import StrictRedis from flask_s…...

Open3D(C++) 最小二乘拟合平面(拉格朗日乘子法)
目录 一、算法原理二、代码实现三、结果展示本文由CSDN点云侠原创,原文链接。 一、算法原理 设拟合出的平面方程为: a x + b y + c...

c语言练习93:环形链表的约瑟夫问题
环形链表的约瑟夫问题 环形链表的约瑟夫问题_牛客题霸_牛客网 描述 编号为 1 到 n 的 n 个人围成一圈。从编号为 1 的人开始报数,报到 m 的人离开。 下一个人继续从 1 开始报数。 n-1 轮结束以后,只剩下一个人,问最后留下的这个人编号是…...

从入门到进阶 之 ElasticSearch 文档、分词器 进阶篇
🌹 以上分享 ElasticSearch 文档、分词器 进阶篇,如有问题请指教写。🌹🌹 如你对技术也感兴趣,欢迎交流。🌹🌹🌹 如有需要,请👍点赞💖收藏&#…...

亚马逊云科技多项新功能与服务,助力各种规模的组织拥抱生成式 AI
从初创企业到大型企业,各种规模的组织都纷纷开始接触生成式 AI 技术。这些企业希望充分利用生成式 AI,将自身在测试版、原型设计以及演示版中的畅想带到现实场景中,实现生产力的大幅提升并大力进行创新。但是,组织要怎样才能在企业…...
网站布局都有哪些?
网站布局是指网页中各元素的布局方式,以下是一些常见的网站布局: 栅格布局:将页面分成一个个小格子,再把内容放到对应的格子中。这种布局有利于提高网页的视觉一致性和用户体验,是网站设计中最常用的布局方式之一。流…...
第17章 MQ(一)
17.1 谈谈你对MQ的理解 难度:★ 重点:★★ 白话解析 MQ也要有一跟主线,先理解它是什么,从三个方面去理解就好了:1、概念;2、核心功能;3、分类。 1、概念:MQ(Message Queue),消息队列,是基础数据结构中“先进先出”的一种数据结构。指把要传输的数据(消息)放在队…...

LeetCode算法刷题(python) Day41|09动态规划|理论基础、509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
目录 动规五部曲LeetCode 509. 斐波那契数LeetCode 70. 爬楼梯LeetCode 746. 使用最小花费爬楼梯 动规五部曲 确定dp数组以及下标的含义确定递归公式dp数组如何初始化确定遍历顺序举例推导dp数组 LeetCode 509. 斐波那契数 力扣题目链接 本题最直观是用递归方法 class Sol…...

Spring(四)
1、Spring6整合JUnit 1、JUnit4 User类: package com.songzhishu.spring.bean;import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component;/*** BelongsProject: Spring6* BelongsPackage: com.songzhishu.spring.bean*…...
2023-10-8讯飞大模型部署2024秋招后端一面(附详解)
1 mybatis的mapper是什么东西 在MyBatis中,mapper是一个核心概念,它起到了桥梁的作用,连接Java对象和数据库之间的数据。具体来说,mapper可以分为以下两个部分: Mapper XML文件: 这是一个XML文件ÿ…...

如何为 Elasticsearch 创建自定义连接器
了解如何为 Elasticsearch 创建自定义连接器以简化数据摄取过程。 作者:JEDR BLASZYK Elasticsearch 拥有一个摄取工具库,可以从多个来源获取数据。 但是,有时你的数据源可能与 Elastic 现有的提取工具不兼容。 在这种情况下,你可…...
Debian11 安装 OpenJDK8
1. 下载安装包 wget http://snapshot.debian.org/archive/debian-security/20220210T090326Z/pool/updates/main/o/openjdk-8/openjdk-8-jdk_8u322-b06-1~deb9u1_amd64.deb wget http://snapshot.debian.org/archive/debian-security/20220210T090326Z/pool/updates/main/o/op…...

[Machine Learning][Part 6]Cost Function代价函数和梯度正则化
目录 拟合 欠拟合 过拟合 正确的拟合 解决过拟合的方法:正则化 线性回归模型和逻辑回归模型都存在欠拟合和过拟合的情况。 拟合 来自百度的解释: 数据拟合又称曲线拟合,俗称拉曲线,是一种把现有数据透过数学方法来代入一条…...

工业自动化编程与数字图像处理技术
工业自动化编程与数字图像处理技术 编程是计算机领域的基础技能,对于从事软件开发和工程的人来说至关重要。在工业自动化领域,C/C仍然是主流的编程语言,特别是用于工业界面(GUI)编程。工业界面是供车间操作员使用的,使用诸如Hal…...
JY61P.C
/** File Name : JY61P.cDescription : attention © Copyright (c) 2020 STMicroelectronics. All rights reserved.This software component is licensed by ST under Ultimate Liberty licenseSLA0044, the “License”; You may not use this file except in complian…...

Go编程:使用 Colly 库下载Reddit网站的图像
概述 Reddit是一个社交新闻网站,用户可以发布各种主题的内容,包括图片。本文将介绍如何使用Go语言和Colly库编写一个简单的爬虫程序,从Reddit网站上下载指定主题的图片,并保存到本地文件夹中。为了避免被目标网站反爬,…...

C++实现分布式网络通信框架RPC(3)--rpc调用端
目录 一、前言 二、UserServiceRpc_Stub 三、 CallMethod方法的重写 头文件 实现 四、rpc调用端的调用 实现 五、 google::protobuf::RpcController *controller 头文件 实现 六、总结 一、前言 在前边的文章中,我们已经大致实现了rpc服务端的各项功能代…...

docker详细操作--未完待续
docker介绍 docker官网: Docker:加速容器应用程序开发 harbor官网:Harbor - Harbor 中文 使用docker加速器: Docker镜像极速下载服务 - 毫秒镜像 是什么 Docker 是一种开源的容器化平台,用于将应用程序及其依赖项(如库、运行时环…...
Qwen3-Embedding-0.6B深度解析:多语言语义检索的轻量级利器
第一章 引言:语义表示的新时代挑战与Qwen3的破局之路 1.1 文本嵌入的核心价值与技术演进 在人工智能领域,文本嵌入技术如同连接自然语言与机器理解的“神经突触”——它将人类语言转化为计算机可计算的语义向量,支撑着搜索引擎、推荐系统、…...

UR 协作机器人「三剑客」:精密轻量担当(UR7e)、全能协作主力(UR12e)、重型任务专家(UR15)
UR协作机器人正以其卓越性能在现代制造业自动化中扮演重要角色。UR7e、UR12e和UR15通过创新技术和精准设计满足了不同行业的多样化需求。其中,UR15以其速度、精度及人工智能准备能力成为自动化领域的重要突破。UR7e和UR12e则在负载规格和市场定位上不断优化…...
实现弹窗随键盘上移居中
实现弹窗随键盘上移的核心思路 在Android中,可以通过监听键盘的显示和隐藏事件,动态调整弹窗的位置。关键点在于获取键盘高度,并计算剩余屏幕空间以重新定位弹窗。 // 在Activity或Fragment中设置键盘监听 val rootView findViewById<V…...

tree 树组件大数据卡顿问题优化
问题背景 项目中有用到树组件用来做文件目录,但是由于这个树组件的节点越来越多,导致页面在滚动这个树组件的时候浏览器就很容易卡死。这种问题基本上都是因为dom节点太多,导致的浏览器卡顿,这里很明显就需要用到虚拟列表的技术&…...

云原生安全实战:API网关Kong的鉴权与限流详解
🔥「炎码工坊」技术弹药已装填! 点击关注 → 解锁工业级干货【工具实测|项目避坑|源码燃烧指南】 一、基础概念 1. API网关(API Gateway) API网关是微服务架构中的核心组件,负责统一管理所有API的流量入口。它像一座…...

iview框架主题色的应用
1.下载 less要使用3.0.0以下的版本 npm install less2.7.3 npm install less-loader4.0.52./src/config/theme.js文件 module.exports {yellow: {theme-color: #FDCE04},blue: {theme-color: #547CE7} }在sass中使用theme配置的颜色主题,无需引入,直接可…...

系统掌握PyTorch:图解张量、Autograd、DataLoader、nn.Module与实战模型
本文较长,建议点赞收藏,以免遗失。更多AI大模型应用开发学习视频及资料,尽在聚客AI学院。 本文通过代码驱动的方式,系统讲解PyTorch核心概念和实战技巧,涵盖张量操作、自动微分、数据加载、模型构建和训练全流程&#…...

jdbc查询mysql数据库时,出现id顺序错误的情况
我在repository中的查询语句如下所示,即传入一个List<intager>的数据,返回这些id的问题列表。但是由于数据库查询时ID列表的顺序与预期不一致,会导致返回的id是从小到大排列的,但我不希望这样。 Query("SELECT NEW com…...