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
API for SpeechAnalytics integration with FreePBX/Asterisk

freepbx_speechanalytics_api API for SpeechAnalytics integration with FreePBX/Asterisk Скопировать файл settings.py.sample в settings.py и отредактиров

Iqtek, LLC 3 Nov 03, 2022
Scripts to convert the Ted-MDB corpora into the formats for DISRPT shared task and the converted corpora

Scripts to convert the Ted-MDB corpora into the formats for DISRPT shared task and the converted corpora.

1 Feb 08, 2022
This program is meant to take the pain out of generating nice bash PS1 prompts.

TOC PS1 Installation / Quickstart License Other Docs Examples PS1 Command Help PS1 ↑ This program is meant to take the pain out of generating nice bas

Steven Hollingsworth 6 Jun 19, 2022
Starscape is a Blender add-on for adding stars to the background of a scene.

Starscape Starscape is a Blender add-on for adding stars to the background of a scene. Features The add-on provides the following features: Procedural

Marco Rossini 5 Jun 24, 2022
Coffeematcher is a python library to randomly match participants for coffee meetings.

coffeematcher coffeematcher is a python library to randomly match participants for coffee meetings. Installation Clone the repository: git clone https

Thomas Wesselink 3 May 06, 2022
Social reading and reviewing, decentralized with ActivityPub

BookWyrm Social reading and reviewing, decentralized with ActivityPub Contents Joining BookWyrm Contributing About BookWyrm What it is and isn't The r

BookWyrm 1.4k Jan 08, 2023
🐍 A Python lib for (de)serializing Python objects to/from JSON

Turn Python objects into dicts or (json)strings and back No changes required to your objects Easily customizable and extendable Works with dataclasses

Ramon Hagenaars 253 Dec 14, 2022
Repositório do Projeto de Jogo da Resília Educação.

Jogo da Segurança das Indústrias Acme Descrição Este jogo faz parte do projeto de entrega do primeiro módulo da Resilia Educação, referente ao curso d

Márcio Estevam da Silva 2 Apr 28, 2022
Programmatic startup/shutdown of ASGI apps.

asgi-lifespan Programmatically send startup/shutdown lifespan events into ASGI applications. When used in combination with an ASGI-capable HTTP client

Florimond Manca 129 Dec 27, 2022
Open slidebook .sldy files in Python

Work in progress slidebook-python Open slidebook .sldy files in Python To install slidebook-python requires Python = 3.9 pip install slidebook-python

The Institute of Cancer Research 2 May 04, 2022
For when you really need to rank things

Comparisonator For when you really need to rank things. Do you know that feeling when there's this urge deep within you that tells you to compare thin

Maciej Wilczyński 1 Nov 01, 2021
Parser for air tickets' price

Air-ticket-price-parser Parser for air tickets' price How to Install Firefox If geckodriver.exe is not compatible with your Firefox version, download

Situ Xuannn 1 Dec 13, 2021
This is the Halloween edition of my Flask Greeting App - HAPPY HALLOWEEEN EVERYONE! :)

HalloweenGreetingApp HAPPY HALLOWEEN EVERYONE! :) This is the Halloween Edition of my Flask Greeting App! Please note, this application is mean to be

Mariya 2 Feb 04, 2022
Generate Gaussian 09 input files for the rotamers of an input compound.

Rotapy Purpose Generate Gaussian 09 input files for the rotamers of an input compound. Distance to the axis of rotation remains constant throughout th

1 Jul 16, 2021
UdemyPy is a bot that hourly looks for Udemy free courses and post them in my Telegram Channel: Free Courses.

UdemyPy UdemyPy is a bot that hourly looks for Udemy free courses and post them in my Telegram Channel: Free Courses. How does it work? For publishing

88 Dec 25, 2022
Always fill your package requirements without the user having to do anything! Simple and easy!

WSL Should now work always-fill-reqs-python3 Always fill your package requirements without the user having to do anything! Simple and easy! Supported

Hashm 7 Jan 19, 2022
Projeto-menu - This project is designed to learn more about control mechanisms in Python programming

Projeto-menu - This project is designed to learn more about control mechanisms in Python programming

Henrik Ricarte 2 Mar 01, 2022
Validate UC alumni identifier numbers with Python 3.

UC number validator Validate UC alumni identifier numbers with Python 3. Getting started Install the library with: pip install -U ucnumber Usage from

Open Source eUC 1 Jul 07, 2021
FollowSpot is a comprehensive audition tracking fullstack web application for entertainment industry professionals.

FollowSpot is a comprehensive audition tracking fullstack web application for entertainment industry professionals. This app allows users to store information/media for all of their auditions while a

Jen Brissman 9 Jul 12, 2022
A data driven app for bicycle hiring in London(UK)

bicycle_hiring_app_deployed A data driven app for bicycle hiring in London(UK). It predicts expected number of bicycle hire in London. It asks users t

Rajarshi Roy Raju 1 Dec 10, 2021