当前位置: 首页 > news >正文

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 是用于创建模块的关键字。模块是一种组织代码的方式&#xff0c;它可以包含函数 (fn)、结构体 (struct)、枚举 (enum)、常量 (const)、其他模块 (mod) 等。模块用于组织和封装代码&#xff0c;帮助将代码分割成可管理的单元。模块可以形成层次结构&…...

C语言实现通讯录(超详细)

1.实现怎样一个通讯录 实现一个通讯录联系人信息&#xff1a;1.可以保存100个人的信息名字2.添加联系人年龄3.删除指定联系人性别4.查找指定联系人电话5.修改指定联系人住址6.排序联系人7.显示所有联系人信息 2.通讯录的实现 2.1创建两个源文件和一个头文件 首先我们创建con…...

【Python机器学习】零基础掌握MinCovDet协方差估计

如何更精准地评估资产的风险和收益? 在投资领域,资产的风险和收益评估是至关重要的。传统的协方差矩阵虽然在某种程度上能反映资产间的关联性,但也存在一定的局限性。例如如果样本数量较少,传统的协方差矩阵可能会出现偏差,从而影响投资决策。 假设现在有一个投资组合,…...

2023年【四川省安全员A证】模拟试题及四川省安全员A证作业模拟考试

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 2023年四川省安全员A证模拟试题为正在备考四川省安全员A证操作证的学员准备的理论考试专题&#xff0c;每个月更新的四川省安全员A证作业模拟考试祝您顺利通过四川省安全员A证考试。 1、【多选题】36V照明适用的场所条…...

Flask项目log的集成

一、引入log 在项目的init.py文件中&#xff1a; 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 的人开始报数&#xff0c;报到 m 的人离开。 下一个人继续从 1 开始报数。 n-1 轮结束以后&#xff0c;只剩下一个人&#xff0c;问最后留下的这个人编号是…...

从入门到进阶 之 ElasticSearch 文档、分词器 进阶篇

&#x1f339; 以上分享 ElasticSearch 文档、分词器 进阶篇&#xff0c;如有问题请指教写。&#x1f339;&#x1f339; 如你对技术也感兴趣&#xff0c;欢迎交流。&#x1f339;&#x1f339;&#x1f339; 如有需要&#xff0c;请&#x1f44d;点赞&#x1f496;收藏&#…...

亚马逊云科技多项新功能与服务,助力各种规模的组织拥抱生成式 AI

从初创企业到大型企业&#xff0c;各种规模的组织都纷纷开始接触生成式 AI 技术。这些企业希望充分利用生成式 AI&#xff0c;将自身在测试版、原型设计以及演示版中的畅想带到现实场景中&#xff0c;实现生产力的大幅提升并大力进行创新。但是&#xff0c;组织要怎样才能在企业…...

网站布局都有哪些?

网站布局是指网页中各元素的布局方式&#xff0c;以下是一些常见的网站布局&#xff1a; 栅格布局&#xff1a;将页面分成一个个小格子&#xff0c;再把内容放到对应的格子中。这种布局有利于提高网页的视觉一致性和用户体验&#xff0c;是网站设计中最常用的布局方式之一。流…...

第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中&#xff0c;mapper是一个核心概念&#xff0c;它起到了桥梁的作用&#xff0c;连接Java对象和数据库之间的数据。具体来说&#xff0c;mapper可以分为以下两个部分&#xff1a; Mapper XML文件&#xff1a; 这是一个XML文件&#xff…...

如何为 Elasticsearch 创建自定义连接器

了解如何为 Elasticsearch 创建自定义连接器以简化数据摄取过程。 作者&#xff1a;JEDR BLASZYK Elasticsearch 拥有一个摄取工具库&#xff0c;可以从多个来源获取数据。 但是&#xff0c;有时你的数据源可能与 Elastic 现有的提取工具不兼容。 在这种情况下&#xff0c;你可…...

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代价函数和梯度正则化

目录 拟合 欠拟合 过拟合 正确的拟合 解决过拟合的方法&#xff1a;正则化 线性回归模型和逻辑回归模型都存在欠拟合和过拟合的情况。 拟合 来自百度的解释&#xff1a; 数据拟合又称曲线拟合&#xff0c;俗称拉曲线&#xff0c;是一种把现有数据透过数学方法来代入一条…...

工业自动化编程与数字图像处理技术

工业自动化编程与数字图像处理技术 编程是计算机领域的基础技能&#xff0c;对于从事软件开发和工程的人来说至关重要。在工业自动化领域&#xff0c;C/C仍然是主流的编程语言&#xff0c;特别是用于工业界面(GUI)编程。工业界面是供车间操作员使用的&#xff0c;使用诸如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是一个社交新闻网站&#xff0c;用户可以发布各种主题的内容&#xff0c;包括图片。本文将介绍如何使用Go语言和Colly库编写一个简单的爬虫程序&#xff0c;从Reddit网站上下载指定主题的图片&#xff0c;并保存到本地文件夹中。为了避免被目标网站反爬&#xff0c…...

高性能日志脱敏组件:已支持 log4j2 和 logback 插件

项目介绍 日志脱敏是常见的安全需求。普通的基于工具类方法的方式&#xff0c;对代码的入侵性太强&#xff0c;编写起来又特别麻烦。 sensitive提供基于注解的方式&#xff0c;并且内置了常见的脱敏方式&#xff0c;便于开发。 同时支持 logback 和 log4j2 等常见的日志脱敏…...

一文读懂PostgreSQL中的索引

前言 索引是加速搜索引擎检索数据的一种特殊表查询。简单地说&#xff0c;索引是一个指向表中数据的指针。一个数据库中的索引与一本书的索引目录是非常相似的。 拿汉语字典的目录页&#xff08;索引&#xff09;打比方&#xff0c;我们可以按拼音、笔画、偏旁部首等排序的目录…...

windows的批量解锁

场景 场景是我从github上拉了一个c#项目启动的时候报错&#xff0c; 1>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets(3327,5): error MSB3821: 无法处理文件 UI\Forms\frmScriptBuilder.…...

Nginx配置微服务避免actuator暴露

微服务一般在扫漏洞的情况下&#xff0c;需要屏蔽actuator健康检查 # 避免actuator暴露 if ($request_uri ~ "/actuator") { return 403; }...

GEE——在GEE中计算地形位置指数TPI

简介: DEM中的TPI计算是指通过计算每个像元高程与其邻域高程的差值来计算地形位置指数(Topographic Position Index)。TPI 是描述地形起伏度和地形形态的一个重要指标,可以用于地貌分类、土壤侵蚀、植被分布等领域。 地形位置指数(Topographic Position Index,TPI)是用…...

树的基本操作(数据结构)

树的创建 //结构结点 typedef struct Node {int data;struct Node *leftchild;struct Node *rightchild; }*Bitree,BitNode;//初始化树 void Create(Bitree &T) {int d;printf("输入结点(按0为空结点):");scanf("%d",&d);if(d!0){T (Bitree)ma…...

Python复刻游戏《贪吃蛇大作战》

入门教程、案例源码、学习资料、读者群 请访问&#xff1a; python666.cn 大家好&#xff0c;欢迎来到 Crossin的编程教室 &#xff01; 曾经有一款小游戏刷屏微信朋友圈&#xff0c;叫做《贪吃蛇大作战》。一个简单到不行的游戏&#xff0c;也不知道怎么就火了&#xff0c;还上…...

SpringCloud之Gateway整合Sentinel服务降级和限流

1.下载Sentinel.jar可以图形界面配置限流和降级规则 地址:可能需要翻墙 下载jar文件 2.引入maven依赖 <!-- spring cloud gateway整合sentinel的依赖--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-s…...

深度学习——深度卷积神经网络(AlexNet)

深度学习——深度卷积神经网络&#xff08;AlexNet) 文章目录 前言一、学习表征二、AlexNet实现2.1. 模型设计2.2. 激活函数2.3. 容量控制与预处理2.4. 训练模型 总结 前言 在前面学习了卷积神经网络的基本原理&#xff0c;之后将继续学习现代卷积神经网络架构。而本章将学习其…...

提高编程效率-Vscode实用指南

您是否知道全球73%的开发人员依赖同一个代码编辑器&#xff1f; 是的&#xff0c;2023 年 Stack Overflow 开发者调查结果已出炉&#xff0c;Visual Studio Code 迄今为止再次排名第一最常用的开发环境。 “Visual Studio Code 仍然是所有开发人员的首选 IDE&#xff0c;与专业…...

广东品牌网站建设/微信推广朋友圈广告

详解Linux命令中&#xff1b;、|、& 、&& 、 ||之间的区别?一、";"分号的用法方式&#xff1a;command1 ; command2用;号隔开每个命令, 每个命令按照从左到右的顺序,顺序执行&#xff0c; 彼此之间不关心是否失败&#xff0c; 所有命令都会执行。二、&q…...

企业怎么做网站建设/google安卓手机下载

在这个系列的***部分里&#xff0c;我们创建了一个电子商务网站&#xff0c;呈示了三类URL:我们通过创建象下面这样一个ProductsController类来处理这些URL&#xff1a;在把上面这个类加到我们的应用中后&#xff0c;asp.net mvc框架就会把进来的URL自动导向到我们的控制器上的…...

怎样在各大网站做推广/广州seo公司推荐

简介 Redis作为目前最常用的K-V缓存数据库&#xff0c;因其具有访问速度快而备受欢迎&#xff0c;而其极快的访问速度是基于数据都在内存中来达到的。但是我们并不能保证服务永远是100%可用的&#xff0c;能保证99.999%可用就已经很了不得了&#xff0c;如果数据仅仅存储于内存…...

网站首页关键字方案/百度seo引流怎么做

一&#xff0e;创建一张HTML页面 初学者创建一张html页面建议借助工具&#xff0c;例如Dreamweaver可视化编辑器。 二&#xff0e;<Script>标签解析 <script>xxx</script>这组标签&#xff0c;是用于在html页面中插入js的主要方法。它主要有以下几个属性&…...

河北网站开发多少钱/如何免费推广一个网站

文章目录流程循环数组简单案例先看看效果图 流程 使用数组的slice() 方法通过条件判断截取原数组相应内容组成新数组 循环数组 let currentPage 0 // arr:原数组 newLen:新数组需要的长度 currentPage:现在的页码// 方法一&#xff1a; function loopData(arr, newLen) {…...

网站备案迁移/流量推广怎么做

01 回溯算法 回溯算法实际上一个类似枚举的搜索尝试过程&#xff0c;主要是在搜索尝试过程中寻找问题的解&#xff0c;当发现已不满足求解条件时&#xff0c;就 “回溯” 返回&#xff0c;尝试别的路径。回溯法是一种选优搜索法&#xff0c;按选优条件向前搜索&#xff0c;以达…...