A weekly dive into commonly used modules in the Rust ecosystem, with story flavor!

Overview

Rust Module of the Week

A weekly dive into commonly used modules in the Rust ecosystem, with story flavor!

Build status

  • Release
    • Rust examples
    • Content
  • Draft
    • Rust examples
    • Content

The goal

The goal of this project is to bring the same concept as PyMOTW to the Rust world. PyMOTW was an invaluable resource for me when I was learning Python years ago, and I hope that I can help someone in a similar way. Each week we'll dive into a module and explore some of the functionality that we can find there while following along the adventures of some colourful characters.

Why the story?

I have always found that I learn better when there's a story behind something I'm learning, a purpose. I've looked at my fair share of documentation but I've found that a lot of code samples can be hard to follow without broader context. So I've decided that every issue will include the story of one or more characters and their problems that only Rust can solve.

Examples

See the examples README for how to run them.

Contributing

Feel free to fork and open Pull Requests about any past or potential future content! I would especially welcome any code feedbacks as I'm sure there'll be lots of chances to improve my code. A proper development guide is planned.

Comments
  • [Error] Compilation error in the first example

    [Error] Compilation error in the first example

    Hi,

    First of all - great initiative.

    I'm a complete Rust noob and this is exactly what I was looking for - an easily digestible, short articles on Rust stdlib.

    Now, when I try to execute the first example:

    use std::{fs, io};
    
    const PHOTO_HOME: &str = "/home/user/motw/week-1/";
    
    fn main() {
        let entries = fs::read_dir(PHOTO_HOME)?
            .map(|entry_res| entry_res.map(|entry| entry.path()))
            .collect::<Result<Vec<_>, io::Error>>()?;
    
        println!("{:?}", entries);
    }
    

    I get the following error:

    error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
      --> src/main.rs:6:43
       |
    5  | / fn main() {
    6  | |     let entries = fs::read_dir(PHOTO_HOME)?
       | |                                           ^ cannot use the `?` operator in a function that returns `()`
    7  | |         .map(|entry_res| entry_res.map(|entry| entry.path()))
    8  | |         .collect::<Result<Vec<_>, io::Error>>()?;
    9  | |
    10 | |     println!("{:?}", entries);
    11 | | }
       | |_- this function should return `Result` or `Option` to accept `?`
       |
       = help: the trait `FromResidual<Result<Infallible, std::io::Error>>` is not implemented for `()`
       = note: required by `from_residual`
    
    error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
      --> src/main.rs:8:48
       |
    5  | / fn main() {
    6  | |     let entries = fs::read_dir(PHOTO_HOME)?
    7  | |         .map(|entry_res| entry_res.map(|entry| entry.path()))
    8  | |         .collect::<Result<Vec<_>, io::Error>>()?;
       | |                                                ^ cannot use the `?` operator in a function that returns `()`
    9  | |
    10 | |     println!("{:?}", entries);
    11 | | }
       | |_- this function should return `Result` or `Option` to accept `?`
       |
       = help: the trait `FromResidual<Result<Infallible, std::io::Error>>` is not implemented for `()`
       = note: required by `from_residual`
    

    Version of Rust in use is:

    stable-x86_64-unknown-linux-gnu (default)
    rustc 1.54.0 (a178d0322 2021-07-26)
    

    Could you provide hints on what could be wrong in my example?

    Thanks in advance!

    opened by matejrisek 2
  • Fix clippy lints

    Fix clippy lints

    In group_files_by_date the clone is not needed. or_insert_withis more efficient in the case where a value already exists, because the closure or function provided to it are only executed if needed, while or_insert always creates the value.

    BTW keep up the good work. I really enjoyed those posts! :)

    opened by Lesstat 1
  • Alternative implementation of visit_dirs

    Alternative implementation of visit_dirs

    fn visit_dirs(dir: &Path) -> io::Result<Vec<PathBuf>> {
        let mut stack = vec![fs::read_dir(dir)?];
        let mut files = vec![];
        while let Some(dir) = stack.last_mut() {
            match dir.next().transpose()? { // r: dir.find_map(|r| r.ok())
                None => {
                    stack.pop();
                }
                Some(dir) if dir.file_type().map_or(false, |t| t.is_dir()) => {
                    stack.push(fs::read_dir(dir.path())?); // stack.extend(fs::read_dir(dir.path()))
                }
                Some(file) => files.push(file.path()),
            }
        }
        Ok(files)
    }
    

    Recursion in Rust isn't specially optimised, so iterative solutions are often faster (in this case 3x). I think it would be good to make a note of this.

    Also, it's often better to just ignore errors returned from the ReadDir since they can have different permission flags etc. In these cases discarding the rest of the results can be overly pessimistic.

    opened by Plecra 1
  • Wrapping up some build automation

    Wrapping up some build automation

    As mentioned in #7 I wanted to have a clean build and release process. It's working for the draft branch, now it's time to bring it to the main branch before content changes/suggestions come in.

    opened by slyons 0
  • Enable continuous testing for examples

    Enable continuous testing for examples

    Enable continuous testing by some means. Whether through doctests or unit tests it would behoove us to have automatic testing and use it as a barrier to any merges.

    opened by slyons 0
  • Run code samples in CI and in the browser

    Run code samples in CI and in the browser

    #9 addresses a bug in one of the code samples. That made me thinking.

    What if we the examples can be tested automatically, similar to Rust's doc tests? Than issue like the one reported in #9 can be prevented.

    And what do you think about making the code sample executable in the web browser? The rust book offers that for many of it's examples.

    opened by OrangeTux 1
  • # std::fs Part 2

    # std::fs Part 2

    Rudgal gets serious about organizing. Will have to include some sort of generating function so the moving/organizing can be demonstrated.

    • DirBuilder
    • Permissions
    • Copying/removing files.
    opened by slyons 0
Releases(published)
Owner
Scott Lyons
Scott Lyons
Reconhecimento de voz, em português, com python

Speech_recognizer Reconhecimento de voz, em português, com python O ato de falar nada mais é que criar vibrações no ar. Por meio de um conversor analó

Marcus Vinícius Ribeiro Andrade 1 Dec 14, 2021
A simple PID tuner and simulator.

PIDtuner-V0.1 PlantPy PID tuner version 0.1 Features Supports first order and ramp process models. Supports Proportional action on PV or error or a sp

3 Jun 23, 2022
Plugins for Agisoft Metashape

Данные плагины предназначены для расширения функциональных возможностей Agisoft Metashape. Плагины представляют собой отдельные программы с собственным интерфейсом, которые запускаются внутри Agisoft

GeoScan 17 Dec 10, 2022
An kind of operating system portal to a variety of apps with pure python

pyos An kind of operating system portal to a variety of apps. Installation Run this on your terminal: git clone https://github.com/arjunj132/pyos.git

1 Jan 22, 2022
How to access and display MyEnergi data

MyEnergi-Python-Example How to access and display MyEnergi data Windows PC Install a version of Python typically 3.10 The Python code here needs addit

G6EJD 8 Nov 28, 2022
A fluid medium for storing, relating, and surfacing thoughts.

Conceptarium A fluid medium for storing, relating, and surfacing thoughts. Read more... Instructions The conceptarium takes up about 1GB RAM when runn

115 Dec 19, 2022
Import Apex legends mprt files exported from Legion

Apex-mprt-importer-for-Blender Import Apex legends mprt files exported from Legion. REQUIRES CAST IMPORTER Usage: Use a VPK extracter to extract the m

15 Dec 18, 2022
synchronize projects via yaml/json manifest. built on libvcs

vcspull - synchronize your repos. built on libvcs Manage your commonly used repos from YAML / JSON manifest(s). Compare to myrepos. Great if you use t

python utilities for version control 200 Dec 20, 2022
Run the Tianxunet software on the Xiaoyao Android simulator

Run the Tianxunet software on the Xiaoyao Android simulator, and automatically fill in the answers of English listening on the premise of having answers

1 Feb 13, 2022
Life Dynamics for python

Daphny_counter run command must be like this: /usr/bin/python3 /home/nmakagonov/Daphny/daphny_counter/Daphny_counter.py -o /home/nmakagonov/Daphny/out

12 Sep 05, 2022
A tool to determine optimal projects for Gridcoin crunchers. Maximize your magnitude!

FindTheMag FindTheMag helps optimize your BOINC client for Gridcoin mining. You can group BOINC projects into two groups: "preferred" projects and "mi

7 Oct 04, 2022
Easy way to build a SaaS application using Python and Dash

EasySaaS This project will be attempt to make a great starting point for your next big business as easy and efficent as possible. This project will cr

xianhu 3 Nov 17, 2022
Gerador do Arquivo Magnético Sintegra em Python

pysintegra é uma lib simples com o objetivo de facilitar a geração do arquivo SINTEGRA seguindo o Convênio ICMS 57/95. Com o surgimento do SPED, muito

Felipe Correa 5 Apr 07, 2022
SHF TEST BACKEND

➰ SHF TEST BACKEND ➿ 🐙 Goals Dada una matriz de números enteros. Obtenga el elemento máximo en la matriz que produce la suma más pequeña al agregar t

Wilmer Rodríguez S 1 Dec 19, 2021
Collection of system-wide scripts that I use on my Gentoo

linux-scripts Collection of scripts that I use on my Gentoo machine. I tend to put all scripts in /scripts directory. It is not likely that you would

Xoores 1 Jan 09, 2022
Pequenos programas variados que estou praticando e implementando, leia o Read.me!

my-small-programs Pequenos programas variados que estou praticando e implementando! Arquivo: automacao Automacao de processos de rotina com código Pyt

Léia Rafaela 43 Nov 22, 2022
Pypot ⚙️ A Python library for Dynamixel motor control

Pypot ⚙️ A Python library for Dynamixel motor control Pypot is a cross-platform Python library making it easy and fast to control custom robots based

Poppy Project 238 Nov 21, 2022
Reference management solution using Python and Notion.

notion-scholar Reference management solution using Python and Notion. The main idea of this app is to allow to furnish a Notion database using a BibTe

Thomas Hirtz 69 Dec 21, 2022
一个可以自动生成PTGen,MediaInfo,截图,并且生成发布所需内容的脚本

Differential 差速器 一个可以自动生成PTGen,MediaInfo,截图,并且生成发种所需内容的脚本 为什么叫差速器 差速器是汽车上的一种能使左、右轮胎以不同转速转动的结构。使用同样的动力输入,差速器能够输出不同的转速。就如同这个工具之于PT资源,差速器帮你使用同一份资源,输出不同PT

Lei Shi 96 Dec 15, 2022
使用京东cookie一键生成所有退会链接

JDMemberCloseLinks 本项目旨在使用京东cookie一键生成所有退会链接

hyzaw 68 Jun 10, 2022