当前位置: 首页 > 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…...

盘古信息PCB行业解决方案:以全域场景重构,激活智造新未来

一、破局&#xff1a;PCB行业的时代之问 在数字经济蓬勃发展的浪潮中&#xff0c;PCB&#xff08;印制电路板&#xff09;作为 “电子产品之母”&#xff0c;其重要性愈发凸显。随着 5G、人工智能等新兴技术的加速渗透&#xff0c;PCB行业面临着前所未有的挑战与机遇。产品迭代…...

中南大学无人机智能体的全面评估!BEDI:用于评估无人机上具身智能体的综合性基准测试

作者&#xff1a;Mingning Guo, Mengwei Wu, Jiarun He, Shaoxian Li, Haifeng Li, Chao Tao单位&#xff1a;中南大学地球科学与信息物理学院论文标题&#xff1a;BEDI: A Comprehensive Benchmark for Evaluating Embodied Agents on UAVs论文链接&#xff1a;https://arxiv.…...

DAY 47

三、通道注意力 3.1 通道注意力的定义 # 新增&#xff1a;通道注意力模块&#xff08;SE模块&#xff09; class ChannelAttention(nn.Module):"""通道注意力模块(Squeeze-and-Excitation)"""def __init__(self, in_channels, reduction_rat…...

oracle与MySQL数据库之间数据同步的技术要点

Oracle与MySQL数据库之间的数据同步是一个涉及多个技术要点的复杂任务。由于Oracle和MySQL的架构差异&#xff0c;它们的数据同步要求既要保持数据的准确性和一致性&#xff0c;又要处理好性能问题。以下是一些主要的技术要点&#xff1a; 数据结构差异 数据类型差异&#xff…...

镜像里切换为普通用户

如果你登录远程虚拟机默认就是 root 用户&#xff0c;但你不希望用 root 权限运行 ns-3&#xff08;这是对的&#xff0c;ns3 工具会拒绝 root&#xff09;&#xff0c;你可以按以下方法创建一个 非 root 用户账号 并切换到它运行 ns-3。 一次性解决方案&#xff1a;创建非 roo…...

Map相关知识

数据结构 二叉树 二叉树&#xff0c;顾名思义&#xff0c;每个节点最多有两个“叉”&#xff0c;也就是两个子节点&#xff0c;分别是左子 节点和右子节点。不过&#xff0c;二叉树并不要求每个节点都有两个子节点&#xff0c;有的节点只 有左子节点&#xff0c;有的节点只有…...

稳定币的深度剖析与展望

一、引言 在当今数字化浪潮席卷全球的时代&#xff0c;加密货币作为一种新兴的金融现象&#xff0c;正以前所未有的速度改变着我们对传统货币和金融体系的认知。然而&#xff0c;加密货币市场的高度波动性却成为了其广泛应用和普及的一大障碍。在这样的背景下&#xff0c;稳定…...

深度学习习题2

1.如果增加神经网络的宽度&#xff0c;精确度会增加到一个特定阈值后&#xff0c;便开始降低。造成这一现象的可能原因是什么&#xff1f; A、即使增加卷积核的数量&#xff0c;只有少部分的核会被用作预测 B、当卷积核数量增加时&#xff0c;神经网络的预测能力会降低 C、当卷…...

IP如何挑?2025年海外专线IP如何购买?

你花了时间和预算买了IP&#xff0c;结果IP质量不佳&#xff0c;项目效率低下不说&#xff0c;还可能带来莫名的网络问题&#xff0c;是不是太闹心了&#xff1f;尤其是在面对海外专线IP时&#xff0c;到底怎么才能买到适合自己的呢&#xff1f;所以&#xff0c;挑IP绝对是个技…...

搭建DNS域名解析服务器(正向解析资源文件)

正向解析资源文件 1&#xff09;准备工作 服务端及客户端都关闭安全软件 [rootlocalhost ~]# systemctl stop firewalld [rootlocalhost ~]# setenforce 0 2&#xff09;服务端安装软件&#xff1a;bind 1.配置yum源 [rootlocalhost ~]# cat /etc/yum.repos.d/base.repo [Base…...