Code Monkey home page Code Monkey logo

easy_rust's People

Contributors

alexanderwillner avatar arcadie avatar cdmurph32 avatar chapeupreto avatar coinbr avatar dhghomon avatar dominikwilkowski avatar elfsternberg avatar encody avatar hoanghun avatar hoijui avatar humancalico avatar jk avatar juanpotato avatar kemra102 avatar ktakayama avatar kumakichi avatar lihz6 avatar max-block avatar maxzinkus avatar mshauneu avatar msilb avatar naereen avatar nisrulz avatar notriddle avatar nrolland avatar phoenixeliot avatar sudo-nice avatar sztheory avatar urbanij avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

easy_rust's Issues

Suggestion: make each snippet compilable

Suggestion: I suggest that each of the over 300 code snippet should be compilable (besides those that fail on purpose).

Approach: I wrote a preliminary little script to extract the snippets: cargo install md2src && md2src && for snippet in $(ls code*.rs); do rustc $snippet ; done. This shows a number of issues and some snippets should be annotated with something like #[doc = "This will fail."].

For a char, use '' instead of ""

In the Chars section, this is stated. However in the following code example, and most of the code examples throughout the README.md, "" is used.

The term `closure` is confused throughout the text.

Throughout the text, the word closure is used in many cases, including the demonstration highlighted in issue 43, even when there is no closure. In the example (which mirrors the example in the text), no free variables (variables outside the function itself, variables that are part of the enclosing lexical scope) are being referenced, so no closure is necessary. The correct term here is not “closure,” it is “anonymous function,” sometimes called a “lambda”. It is only a closure if it in some way captures (encloses) values from the surrounding context.

Consider the following demonstration, in which the anonymous function described in Issue 43 is replaced with a named function:

fn stringify(i: &u64) -> String {
        format!("{}", i)
}

fn main() {
        let x = [1, 2, 3, 4, 5];
      
        // let z = x.iter().map(|&x| format!("{}", x)).collect::<Vec<String>>();
       
        let z = x.iter().map(stringify).collect::<Vec<String>>();
        println!("{:?}", z);
}

The functionality is unchanged. Since this function is small, used only once, and not pub, I would expect the compiler to in-line it. Examining the produced assembly language shows that that is the case; the assembly from both the anonymous and named versions is exactly the same. There is no performance loss at all by naming the function.

Don’t take this as too strong a criticism! I absolutely want to commend you on this work! Something this clear and concise has long been needed, and I think you’ve hit a powerful sweet spot between helping newcomers and giving good reminders to experienced old-timers. I want the work to be better, and this, the typing and naming of functions that can be passed to other functions, higher-order programming, was one of the hardest things for me to understand, and I don’t want anyone else to go through that kind of confusion.

Chapter "Taking user input"

Hi,

at the end of chapter "Taking user input" you explain how to access environment variables which looks good to me until you introduce the env! macro.

As environment variables are usually queried while the program is run and not while it is compiled, I think that the last section (beginning with the sentence "The easiest way to get a single Var is by using the env! macro.") is actually not what you are trying to show.

From the Rust documentation {1}:

Macro std::env
Inspects an environment variable at compile time.

The same applies to the option_env! macro (which you incorrectly call option_str! twice in the text but use correctly in the code example).

If you really want to show how environment variables can be checked while compilation then this should be made clear in the text.

Regards,

Uwe

[1] https://doc.rust-lang.org/std/macro.env.html

createPdfFromReadme.sh failed

LaTeX Warning: File `https://github.com/Dhghomon/easy_rust/workflows/github\%20
pages/badge.svg' not found on input line 119.


! LaTeX Error: File `https://github.com/Dhghomon/easy_rust/workflows/github%20p
ages/badge.svg' not found.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.119 ...rust/workflows/github\%20pages/badge.svg}
 l/easy_rust.tex+                                                                                                                                                                                                                           buffers


! LaTeX Error: Cannot determine size of graphic in https://github.com/Dhghomon/
easy_rust/workflows/github%20pages/badge.svg (no BoundingBox).

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.119 ...rust/workflows/github\%20pages/badge.svg}

[1] [2] [3] [4] [5]
Overfull \hbox (159.71255pt too wide) in paragraph at lines 709--715
\TU/lmtt/m/n/10 111111111111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111111111111111111111111111110110\TU/lmr/m/n/10
 .

xdvipdfmx:fatal: Image inclusion failed for "https://github.com/Dhghomon/easy_rust/workflows/github%20pages/badge.svg".

No output PDF file written.
[6Generated PDF file easy_rust.pdf

workaroud I found:

diff --git a/README.md b/README.md
index 4af16d2e7647..32f7004e2d6b 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,5 @@
 ## Updates
-![example workflow name](https://github.com/Dhghomon/easy_rust/workflows/github%20pages/badge.svg)
+<!-- ![example workflow name](https://github.com/Dhghomon/easy_rust/workflows/github%20pages/badge.svg) -->

 23 May 2021: [Now available in Indonesian](https://github.com/ariandy/easy-rust-indonesia) thanks to [Ariandy](https://github.com/ariandy)/[1kb](https://1kilobyte.github.io/).

[Typo] Milliseconds instead of microseconds

At the end of the readme it says:

1.025µs
683.378µs

So that's just over 1 microsecond vs. 683 milliseconds. We can see that Rust did take some time to do it.


This is 683 microseconds not milliseconds.
Just a little typo ahah, thx for the good work 😃

Code examples in "Option" chapter

Hi,

most examples in the "Option" chapter are wrong. The second example contains if value.len() < 5 and is correct, the following examples contain if value.len() < 4 and don't catch the case where value.len() == 4. In all examples you access value[4] in the else branch.

Regards,

Uwe

Incomplete line?

Please, search for the line: Now let's make one more thread. Each thread
It looks like it's incomplete.

Add Persian(Farsi) translation

Hi, thank you for making this document.
BTW, I translated this document into Farsi(Persian), I think it would be good to give a link to it, maybe it will help someone :)
Its Farsi translation can be found at this link.

epub version (How To)

I am not sure of the best way to approach this (to officially support on your end or not), but I generated an epub for the book using https://github.com/Michael-F-Bryan/mdbook-epub.

Steps

  • Since I am on Ubuntu, I had to update the createBookFromReadme.sh to use the csplit command (search and replace).
  • On Ubuntu I had to search and replace mdBook with mdbook in the script as well.
  • Installed mdbook with cargo install mdbook --version 0.3.7 (the epub requires an older version)
  • installed mdbook-epub with cargo install mdbook-epub
  • Removed the data before "## Introduction" in the README.md due to a missing SVG file.
  • added [output.epub] to the bottom of book.toml
  • ran createBookFromReadme.sh - this results in the web preview having a 404, can ignore, and just ctrl-c to kill the script.
  • The epub should be in the book directory

I just wanted to share the process in case any others wanted to add the book to a reader, etc.

In `impl Trait`, the description of typing is incorrect.

The text says that B in the section on .map() is of type Self; this is incorrect.

Consider the following demonstration (this code compiles under Rust 2018 as a drop in for the contents of main.rs after cargo new mapdemo --bin; cargo run):

fn main() {
        let x = [1, 2, 3, 4, 5];
        let z = x.iter().map(|&x| format!("{}", x)).collect::<Vec<String>>();
        println!("{:?}", z);
}

The self argument to map will be an Iter<u64>. The Self::Item type is therefore u64. The return type of the function being passed to map is String. This is what the B type variable indicates: the return type of the function, as can be clearly seen in the second line of the where clause in your example:

    F: FnMut(Self::Item) -> B

I have left a pull request: #42

github-pages workflow deploy fail

From recent change, the deploy is fail due to:

Run peaceiris/actions-mdbook@v1
mdbook version: 0.4.21
Operating System: unknown-linux-gnu
toolURL: https://github.com/rust-lang/mdBook/releases/download/v0.4.21/mdbook-v0.4.21-x86_64-unknown-linux-gnu.tar.gz
/bin/tar xz --warning=no-unknown-keyword -C /home/runner/tmp -f /home/runner/work/_temp/bc8b8fa7-2411-4a7b-b503-cecaabd29ffd
/home/runner/toolbin/mdbook --version
/home/runner/toolbin/mdbook: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.29' not found (required by /home/runner/toolbin/mdbook)
/home/runner/toolbin/mdbook: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by /home/runner/toolbin/mdbook)

Run mdbook build
mdbook: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.29' not found (required by mdbook)
mdbook: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by mdbook)
Error: Process completed with exit code 1.

It has been reported to actions-mdbook: peaceiris/actions-mdbook#464

Another issue is there is no package: linuxbrew-wrapper in runner-image ubuntu 20.04/2.04 (see this action run of #151 ). #50 should address this issue.

Suggestion: Make this a book/HTML with the Rust project `mdbook`

Great work, do you have any thoughts on making this a website with the Rust project mdbook by converting markdown -> html and hosting on GitHub pages?

mdbook allows you to invoke the Rust Playground directly, provides search and organisation of pages plus a number of other cool features.

I'm happy to contribute a PR 😄

Chapter "RwLock"

Hi,

in chapter "RwLock" you list the rules applying to a RwLock variable:

  1. many .read() variables is okay,
  2. one .write() variable is okay,
  3. but more than one .read() or .read() together with .write() is not okay.

I think rule 3 should read: but more than one .write() or .read() together with .write() is not okay.

Regards,

Uwe

Introduce the inclusive range at the same time as the exclusive one, for clarity.

In the Arrays section the range syntax is explained, but only the exclusive one (..), not the inclusive (..=):
* Index ranges are exclusive (they do not include the last number)

It is later used in an example in Enums section without an explicit explanation (and before that it shows in compiler output):
6..=18 => ThingsInTheSky::Sun, // Between 6 and 18 hours we can see the sun

The inclusive syntax is not properly explained until Loops:
* ..= creates an inclusive range: 0..=3 = 0, 1, 2, 3.

I think it may be clearer to have it both options layed out the first time. or at least link to the full explanation from there. Because right now it kind of gives the impression that ranges for Arrays can not ever be inclusive.

use Verbs instead of Nouns for trait examples

Rust is not an OOP language and does not support OOP patterns. There's a good thread about this on the Official Rust Users forum where people suggest calling Rust a Behavior-Oriented Programming language so as to clearly distinguish it from OOP.

I'd like to point out that all the traits in the standard library can be easily mapped to verbs or actions like:

  • Display means the type is displayable
  • Copy means the type is copyable
  • Iterator means the type is iterable
  • and so on

In your document you use trait Dog as an example which kinda makes sense in an OOP-sense but not really in a BOP-sense since what verb or action does a noun like Dog map to? If a type implements Dog it's barkable, walkable, pettable? I'd argue all of those properties should be their own traits. I know the whole Animal thing is a super popular example in OOP languages so it's tempting to re-use it to try to explain Rust traits but I think it's generally more misleading than helpful as it reinforces the misconception that Rust is OOP.

I can't tell you off the top of my head what would be a better example but just anything where the trait name is a Verb and not a Noun would be better.

Consistently style traits with italics

I think, we can make traits more stand out throughout the doc by applying some consistent style to it. I was thinking about using italics, if you had no plans for that style already. Now the traits are sometimes bold and sometimes just a plain text. Using italics would make lines like:

String is not Copy, so my_closure() is Fn: it takes a reference.
You can see for example Copy, Debug, and Display.

...to look like:

String is not Copy, so my_closure() is Fn: it takes a reference.
You can see for example Copy, Debug, and Display.

What do you think?

Replacing "incomplete snippet" etc. with emojis

@AlexanderWillner The thought just occurred to me that the (Note: this will not compile) and "incomplete code snippet" notations could each be replaced with an emoji to improve readability and keep new users from being distracted when reading the code samples. Would that work with the script you've made though? I was thinking of these two:

🚧
https://unicode.org/emoji/charts/full-emoji-list.html#1f6a7


https://unicode.org/emoji/charts/full-emoji-list.html#2049

The first is for the incomplete code snippets, and the second for code that needs a fix to compile, and of course they could be put together as well for code that matches both. Then all I would need to do is add a quick explanation at the beginning of the book in the same way that the Rust Book does with the crab images they use to give a hint that the code won't work.

Chapter "Other macros"

Hi,

you list file! as one of the debug macros but then forget about it the listing and code example that follows.

Regards,

Uwe

Vietnamese translation

Hello there,

Can I do translation of this book to Vietnamese ? I am translating official book too and sure will start on this when I finish that.

best regards,
v.

Chapter "Using files"

Hi,

some things that caught my eye in the "using files" chapter:

  1. The second version of the first code example returns Ok(88) and Ok(5) which is correct, yet you state: "The first one doesn't work, but the second one does." I don't know what you're trying to say here.
  2. There's a type with apostrophe and backtick in the sentence "So it is a Result<T, Error>', but we only need to write the Result` part."
  3. The comment in the first file example code is wrong: std::fs::File::create will not delete a file that already exists, it will only delete the content (truncate). This is an important distinction because the file system entry of the file does not change, only the size does.
  4. The same applies to std::fs::write: it will only remove the content of an already existing file, not the file itself.

Thanks for your effort in creating Rust in Easy English.

Regards,

Uwe

Animal, not AnimalType

Love the tutorial! This is my introduction to Rust, so thank you!

In the section "Implementing structs and enums" it says that Self means AnimalType. This point is repeated a few times in this section and the following. But if I'm not completely mistaken, isn't Self = Animal instead of AnimalType?

@ can be used without the value

And when you use @, you have to use the value. It will give an error if you don't:

error: 1 positional argument in format string, but no arguments were given
--> src\main.rs:4:30
|
4 | number @ 13 => println!("{} is unlucky in North America, lucky in Italy! In bocca al lupo!"),

The provided error is because you used {} without a positional argument.

This works perfectly fine:

fn match_number(input: i32) {
    match input {
    number @ 4 => println!("{} is an unlucky number in China (sounds close to 死)!", number),
    number @ 13 => println!("thirteen is unlucky in North America, lucky in Italy! In bocca al lupo!"),
    _ => println!("Looks like a normal number"),
    }
}

fn main() {
    match_number(13);
}
thirteen is unlucky in North America, lucky in Italy! In bocca al lupo!

This is a great Rust guide!

I've tried to find your email or a way to direct message you, but I couldn't, so I'm using this GH issue. Would you consider writing a similar book for EdgeDB? We'd love to contract you for that. Here's a blog post about EdgeDB that gives an idea about the project: https://edgedb.com/blog/edgedb-a-new-beginning. If you dive deep you'll fine that in many ways EdgeDB and Rust are very similar :)

Please email me at [email protected] if you are interested.

Incorrect terminology in 'Implementing structs and enums'

The chapter calls everything in an impl block 'methods', and functions that don't take self 'associated methods or static methods'. This is incorrect terminology according to the Book, the Reference, etc. It should be that everything in an impl block is 'associated functions', everything specifically in an impl Foo block as opposed to a trait impl 'inherent functions', and functions with a self parameter 'methods'. 'Static methods' is entirely Java terminology; you wouldn't use it for the same reason you don't call structs classes.

Consider using into_iter instead of iter in the library example

The following example consumes the books instead of returning references. I think this fits better with the into_iter description.

impl Iterator for Library {
type Item = String;

fn next(&mut self) -> Option<String> {
    match self.books.pop() {
        Some(book) => Some(book + " is found!"), // Rust allows String + &str
        None => None,
    }
}

}

[WIP] Spanish translation | Traducción al español

🇺🇸 I have started translating Easy Rust into Spanish. If you want to collaborate, you can do it in this repository: easy_rust_es
Tips or discussions on terminology and grammar are also welcome in the issues section.

🇪🇸 He empezado a traducir Easy Rust al español. Si quieres colaborar, puedes hacerlo en este repositorio: easy_rust_es
También son bienvenidos los consejos o discusiones sobre terminología y gramática en la sección issues.

Char type in chapter Types -> Primitive types

Hi,

this sentence confuses me:
All chars are 4 bytes. They are 4 bytes because some characters in a string are more than one byte. Basic letters that have always been on computers are 1 byte, later characters are 2 bytes, and others are 3 and 4. A char needs to be 4 bytes so that it can hold any kind of character.

It would probably better to rephrase

All chars take 4 byte in memory so they can represent all Unicode elements. Basic letters will only take 1 byte out of the available 4 bytes, other letters like German Umlauts will require 2 bytes and e.g. Korean, Japanese or Chinese signs will require 3 or all 4 bytes.
Strings on the other hand are encoded in UTF-8 and thus use the minimal memory footprint required to hold the letters in the string.

Also the example does not show what I think is intended:

fn main() {
    println!("{}", "a".len()); // .len() gives the size in bytes
    println!("{}", "ß".len());
    println!("{}", "国".len());
    println!("{}", "𓅱".len());
}

If it should show the size of the chars, the output should always be "4" and the example should use single apostrophes '. But that would not compile because the char type does not have a len() method.

What it actually shows is the length of the UFT-8 encoded string. Which is a significant difference to the length of a char, which is always 4.

You might want to change the code example to:

fn main() {
    println!("Size of a char: {}", std::mem::size_of::<char>());
    println!("Size of string containing 'a': {}", "a".len()); // .len() gives the size in bytes
    println!("Size of string containing 'ß': {}", "ß".len());
    println!("Size of string containing '国': {}", "国".len());
    println!("Size of string containing '𓅱': {}", "𓅱".len());
}

Regards,

Uwe

Using ```code``` for inlined code chunks

I see you use triple backticks (```code```) style for inlined code as well. Is there a specific reason for that? Because I'm going to open some PRs and I wonder if it's Ok to use single backticks (`code`) for that?
I can convert all the triplets to the single ones where appropriate, for the sake of consistency, if you'd like.

Incorrect/shuffled index order when running createBookFromReadme.sh

I wanted to contribute to the project.
Issue/Bug :
Currently the index in the side menu and the index in the URL has a difference of 1.
e.g. The updates page has a index number 1 in side menu but in URL it shows Chapter_0.html.
To rectify this index mismatch. I just awk-ed each Chapter filename after it is generated and increased the index by 1.
e.g. Chapter_0.md -> Chapter_1.md
But every time I am building the project using createBookFromReadme.sh, the SUMMARY.md file is different and generated with shuffled index.
Am I doing something wrong while building.

OS : Ubuntu 22.04
Steps to reproduce :
Modify gcsplit to csplit
Run ./createBookFromReadme.sh

section on arrays in the tour of the standard library is outdated

The explanation is no longer valid as the following code works fine
The array implements the IntoIterator trait, and the for loop results in an implicit call to .into_iter().

fn main() {
    // ⚠️
    let my_cities = ["Beirut", "Tel Aviv", "Nicosia"];

    for city in my_cities {
        println!("{}", city);
    }
}

"LOWERCASE" error in "Taking User Input"?

Hi. New to rust so maybe I'm wrong... I tried the example in "Taking User Input" where you use "cargo run LOWERCASE Does this work too?" and it did not convert "Does" to lower case, as shown in the book online here: https://dhghomon.github.io/easy_rust/Chapter_63.html ... If "LOWERCASE" matched "lowercase" in the "match" , it would imply that that match on a string would be case insensitive. I think you just need to change "LOWERCASE" to "lowercase" in the example run.

as considered harmful

Using the as keyword is considered harmful; it silently panics when value are out of range, and it's not explicit about it. Consider replacing:

fn main() {
    let my_number = 100;
    println!("{}", my_number as u8 as char);
}

with:

use std::convert::TryFrom;

fn main() {
    let my_number = 100;
    println!("{}", u8.try_from(my_number).unwrap() as char);
}

Since this a tutorial, I think it would be better to write:

fn main() {
    let my_number = 100 as u8;
    println!("{}", my_number as char);
}

or:

fn main() {
    let my_number: u8 = 100;
    println!("{}", my_number as char);
}

or:

fn main() {
    let my_number = 100u8;
    println!("{}", my_number as char);
}

which are all equivalent, but mean something slightly different to the original code, so you'd need to adjust the text slightly.

(None of these solutions feel good enough for inclusion. Maybe you could take a brief tangent to point out the problem with using as? But panicking hasn't been introduced yet…)

createBookFromReadme.sh doesn't work

macOS 10.15.7

bash createBookFromReadme.sh
2020-12-19 14:48:44 [WARN] (mdbook::book::summary): Expected a start of a link, actually got Some(Text(Borrowed("[")))
2020-12-19 14:48:44 [ERROR] (mdbook::utils): Error: Summary parsing failed
2020-12-19 14:48:44 [ERROR] (mdbook::utils): 	Caused By: There was an error parsing the numbered chapters
2020-12-19 14:48:44 [ERROR] (mdbook::utils): 	Caused By: There was an error parsing the numbered chapters
2020-12-19 14:48:44 [ERROR] (mdbook::utils): 	Caused By: failed to parse SUMMARY.md line 3, column 3: The link items for nested chapters must only contain a hyperlink

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.