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网站上下载指定主题的图片,并保存到本地文件夹中。为了避免被目标网站反爬,…...

TDengine 快速体验(Docker 镜像方式)
简介 TDengine 可以通过安装包、Docker 镜像 及云服务快速体验 TDengine 的功能,本节首先介绍如何通过 Docker 快速体验 TDengine,然后介绍如何在 Docker 环境下体验 TDengine 的写入和查询功能。如果你不熟悉 Docker,请使用 安装包的方式快…...
React Native 开发环境搭建(全平台详解)
React Native 开发环境搭建(全平台详解) 在开始使用 React Native 开发移动应用之前,正确设置开发环境是至关重要的一步。本文将为你提供一份全面的指南,涵盖 macOS 和 Windows 平台的配置步骤,如何在 Android 和 iOS…...

基于ASP.NET+ SQL Server实现(Web)医院信息管理系统
医院信息管理系统 1. 课程设计内容 在 visual studio 2017 平台上,开发一个“医院信息管理系统”Web 程序。 2. 课程设计目的 综合运用 c#.net 知识,在 vs 2017 平台上,进行 ASP.NET 应用程序和简易网站的开发;初步熟悉开发一…...
QMC5883L的驱动
简介 本篇文章的代码已经上传到了github上面,开源代码 作为一个电子罗盘模块,我们可以通过I2C从中获取偏航角yaw,相对于六轴陀螺仪的yaw,qmc5883l几乎不会零飘并且成本较低。 参考资料 QMC5883L磁场传感器驱动 QMC5883L磁力计…...
鸿蒙中用HarmonyOS SDK应用服务 HarmonyOS5开发一个医院查看报告小程序
一、开发环境准备 工具安装: 下载安装DevEco Studio 4.0(支持HarmonyOS 5)配置HarmonyOS SDK 5.0确保Node.js版本≥14 项目初始化: ohpm init harmony/hospital-report-app 二、核心功能模块实现 1. 报告列表…...
OpenPrompt 和直接对提示词的嵌入向量进行训练有什么区别
OpenPrompt 和直接对提示词的嵌入向量进行训练有什么区别 直接训练提示词嵌入向量的核心区别 您提到的代码: prompt_embedding = initial_embedding.clone().requires_grad_(True) optimizer = torch.optim.Adam([prompt_embedding...
[Java恶补day16] 238.除自身以外数组的乘积
给你一个整数数组 nums,返回 数组 answer ,其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。 题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。 请 不要使用除法,且在 O(n) 时间复杂度…...
OpenLayers 分屏对比(地图联动)
注:当前使用的是 ol 5.3.0 版本,天地图使用的key请到天地图官网申请,并替换为自己的key 地图分屏对比在WebGIS开发中是很常见的功能,和卷帘图层不一样的是,分屏对比是在各个地图中添加相同或者不同的图层进行对比查看。…...
稳定币的深度剖析与展望
一、引言 在当今数字化浪潮席卷全球的时代,加密货币作为一种新兴的金融现象,正以前所未有的速度改变着我们对传统货币和金融体系的认知。然而,加密货币市场的高度波动性却成为了其广泛应用和普及的一大障碍。在这样的背景下,稳定…...

Linux --进程控制
本文从以下五个方面来初步认识进程控制: 目录 进程创建 进程终止 进程等待 进程替换 模拟实现一个微型shell 进程创建 在Linux系统中我们可以在一个进程使用系统调用fork()来创建子进程,创建出来的进程就是子进程,原来的进程为父进程。…...