Giter VIP home page Giter VIP logo

rust-by-example's Introduction

Rust By Example

Build Status

Learn Rust with examples (Live code editor included)

Using

If you'd like to read Rust by Example, you can visit https://doc.rust-lang.org/rust-by-example/ to read it online.

If you'd like to read it locally, install Rust, and then:

git clone https://github.com/rust-lang/rust-by-example
cd rust-by-example
cargo install mdbook
mdbook build
mdbook serve

To be able to run the examples, you must be connected to the internet; you can read all content offline, however!

The following warnings can be ignored safely.

[WARN] (mdbook::preprocess::cmd): The command wasn't found, is the "gettext" preprocessor installed?
[WARN] (mdbook::preprocess::cmd):   Command: mdbook-gettext

Using translated version

If there is a translated resource in po/ directory, it can be specified through MDBOOK_BOOK__LANGUAGE like below:

git clone https://github.com/rust-lang/rust-by-example
cd rust-by-example
cargo install mdbook
MDBOOK_BOOK__LANGUAGE=ja mdbook build
MDBOOK_BOOK__LANGUAGE=ja mdbook serve

Contributing

Please see the CONTRIBUTING.md file for more details.

Translating

Please see the TRANSLATING.md file for more details.

Translating guide for each languages

Translations to other languages

License

Rust by Example is licensed under either of

at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Rust by Example by you, as defined in the Apache-2.0 license, shall be dually licensed as above, without any additional terms or conditions.

rust-by-example's People

Contributors

adamchalmers avatar andymac-2 avatar bmusin avatar brson avatar dalance avatar dbbrian avatar ehuss avatar epage avatar francozappa avatar frewsxcv avatar funkill avatar gurgalex avatar hosseinassaran avatar jsjoeio avatar juleskers avatar kberov avatar klampworks avatar lovasoa avatar maccoda avatar marioidival avatar mark-i-m avatar mdinger avatar projektir avatar quietmisdreavus avatar spastorino avatar steveklabnik avatar tomasz-rozanski avatar ubsan avatar xiaochuanyu avatar xmasreturns 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

rust-by-example's Issues

Clean up examples

Examples should always print something to the console, and should not throw warnings.

The warnings usually come from unused variables, we should try to always use all the variables we declare, and in cases where this is not possible we can prepend the variable with an underscore to silence the warning.

Restructure the book

I'm thinking of doing some changes to the book structure:

  • Break some "chapters" into "subchapters". For example, the borrowing chapter is very long because it contains 5 (!) concepts, and each concept has one example, I think it'll be easier for the reader if we break it down like this:
Borrowing
|-- References
|-- Mutability
|-- Freezing
|-- Aliasing
`-- The `ref` pattern
  • Because of the previous point and with the upcoming of the live code editor (#73), I think it'll be better to have only one program (i.e. one editor) per page.

The goal is to keep each page bite-sized, i.e. one concept/idea/example/editor per page.

I'll like to know if others think this is a good idea, or if you have any suggestion.

cc @kud1ing @vojtechkral @vks @zslayton

Typo on move example

One of the move examples (assignment.rs) states starting at line 16:

// copy `b` into `a`, now both point to the same heap allocated data
...
let b = a;

Unless I'm mistaken, that should read

// copy `a` into `b`... 

Derivable traits are not particularly special

http://rustbyexample.com/examples/trait/README.html

Rust provides a special kind of traits, named deriving traits

Traits which can be derived are totally normal traits, just the #[deriving] syntax extension that is built-in to the compiler understand how to create a basic impl for them. Also, the text as written seems to imply they can't be implemented by hand which is false.

(Also, they aren't called "deriving traits": one could describe them as "derivable traits", I guess.)

Incorrect output in Structs

Your struct Point has 2 variables with f64 type, and you instantiate Point with { x: 3.0, y: 4.0}, but your println! output shows integer type: "Point coordinates: (3, 4)"

Syntax coloring

What happened to the beautiful dark-background syntax coloring?

Minor grammar mistake on Bounds page

When writing generic code, is important

Should be

When writing generic code, it is important

Also, technically to make correct grammatical sense, the whole heading should either be

When writing generic code, it is important to bound the generic data to conform to some traits; this allows using the trait methods in these bounded implementations.

or

When writing generic code, it is important to bound the generic data to conform to some traits. This allows using the trait methods in these bounded implementations.

Note the semicolon or splitting of the sentence where the second comma was.

Fix travis, old snapshot is making all the test fail

Travis is not using the "real" rust nightly build. Instead is using an old snapshot with date 18th April, making all the tests fail.

cc @jacob-hegna Any idea on why is this happenig? According to the PPA there should be an snapshot from 30th April available for Ubuntu 12.04 (a.k.a. Precise Pangolin)

extend overloading example by mentioning macros

Currently only traits are mentioned in the overloading example. They only work if the functions to be overloaded have the same number of arguments. Using macros it is possible to have more generic overloading. See for example this implementation of a Python-like range:

#![feature(macro_rules)]

use std::iter::range_step;

macro_rules! range (
    ($start:expr, $end:expr, $step:expr) => (
        range_step($start, $end, $step)
    );
    ($start:expr, $end:expr) => (
        range($start, $end)
    );
    ($end:expr) => (
        range(0, $end)
    );
)

Errrs in the array section

There is an error in the array section:

// len() returns the size of the array
println!("array size: {}", xs.last());

And analyze is misspelled.

Topics for the JSON chapter

This is what I have in mind at the moment (but we should try to reduce the number of topics by merging some of them)

  • Custom Encoding/Decoding (to Structs)
  • Decoding from &str
  • Default Decoding/Encoding #[deriving(Encodable,Decodable)]
  • Encoding to String
  • Error handling (DecoderError, ParserError, etc)
  • Streaming (which is not documented)
  • The Json intermediate struct
  • ToJson
  • How JSON types match to Rust types: null <-> None, [] <-> Vec, "" <-> String, Object <-> TreeMap<String, T>/HashMap<String, T>

Feedback is welcome!

Order-wise, this chapter should be after the "hashmap"/"treemap" chapters.

The structure of the chapter should look like this (some topics are still missing):

.
|-- `Json` -> The `Json` enum and its variants
|   |-- Decoding -> `json::from_str` + `BuilderError`
|   |-- `ToJson`` -> struct -> `Json`
|   `-- Stringify??? -> `Json` -> `String`
|-- `Decoder` -> `Json` -> `Decoder` -> `T` - where `T` = `Vec`, `String`, `HashMap`, etc
|-- `Decodable` -> `#[deriving(Decodable)]`
|   `-- Custom??? -> Manually implement `Decodable`
`-- `Encodable` -> `#[deriving(Encodable)]`, `str_encode`
    `-- Custom??? -> Manually implement `Encodable`

@vojtechkral is working on this

Typo on lifetimes example

On the Lifetimes chapter, the first example states at line 6:

    let stack_integer = 5; // 'a starts ────────────────────────────────┐ │
    let boxed_integer = box 4; // 'b starts ──────────────────────────┐ │ │

...but neither of those are called a or b, and the example not even compiles, obviously.

I'm not sure if this was on purpose or not, hence my issue and not a PR 😄

Rust Playpen Integration

Some of the Rust devs have put together a site that lets you experiment with Rust code, seeing output as well as asm/ir.

It would be really helpful to provide a link to launch each of the source files in the playpen so readers could toy with the examples on their own.

The site understands links in the format:

http://playtest.rust-lang.org/?code=fn+main()+{+println!(%22foo%22)+}&run=1

There's also a CORS-enabled API that supports directly submitting code via POST if that's more interesting.

I'm happy to help code this if someone can describe the best way to go about adding this functionality.

Add a "rustic" theme

A gitbook plugin can be used to add a new theme to the book. It'll be nice if we could match the default theme of the book to the theme used by rust-lang.org

Lifetimes are confusing

Hi, thanks for the guide, it's helping a lot! I'm stuck on lifetimes though - I don't think it's quite clear what they are / what they're used for. I'd propose changes, but not sure if I understand it well enough to do so.

It might be good to introduce the special 'static lifetime as well, since it's used in the following section without an explanation.

Operator & is used without being introduced

In section 15, "Box, stack and heap", the & operator is used without being mentioned. (Maybe it is not supposed to be explain in this section but at least it should be mentioned that the operator is purposely not introduced here and will be explained later.)

Extend traits chapter

  • supertraits FooBar: Foo + Bar
  • trait objects Box<Foo>, &Foo
  • "function overloading" using double dispatch: Vec * Vec and Vec * int

Pattern matching `ref` could be mentioned more prominently

The first introduction is "hidden" at the bottom of http://rustbyexample.com/examples/borrow/README.html

ref is one of the most useful & powerful parts of pattern matching, it makes working with the interior borrowed data possible (it wouldn't be without ref). It would probably be good to explain why it's necessary: stealing ownership of data from behind a reference & is fundamentally wrong. (FWIW, it's used with a brief mention in http://rustbyexample.com/examples/enum/README.html but it isn't explained why one "can't move tail out of the list".)

Also, I don't see a mention of ref mut anywhere.

TODO Examples

These are some topics that need examples, but not I'm too familiar with. It would be great if someone more familiar with these topics could send a PR adding examples for these topics.

  • Procedural macros #155
  • Any
  • Arc #104
  • Ascii
  • Cell
  • Gc
  • Mutex #105
  • Once
  • Rc
  • RefCell
  • Unsafe<T>
  • bitflags
  • green #[start] and rustuv::event_loop vs basic::event_loop
  • local_data
  • log crate
  • net::tcp
  • rustdoc #108

These are topics that I can cover, and some already appear in the book as unavailable. But I won't get angry if someone wants to give me a hand :-).

  • Bottom types ! #146
  • FFI #114
  • Phantom types #145
  • Barrier #113
  • Buffered{Reader,Writer}
  • assert!, debug_assert!, etc.
  • macros_rules #110
  • os::args + getopts #106
  • rand #116
  • regex crate
  • select!
  • serialize::json #86
  • std::hash + collections::hashmap #161
  • std::io::stdio
  • term crate
  • unsafe blocks #112
  • url crate
  • bench #115
  • closures #91
  • comments: //, /* */, /* /* */ */, ///, etc. #107
  • formatting #196
  • kinds: Send, Share, Copy and Sized
  • raw pointers *T #112
  • tasks #113
  • testing #111
  • unsafe global state (static mut) #112
  • Drop
  • Process
  • Result and try!
  • std::io::fs
  • attributes: #[test], #[crate_id], etc
  • file I/O
  • modules and crates
  • operator overloading: Add, Sub, etc.
  • simd

Tuples: what about tuples with only one member?

E.g. in Python there is a problem when you try to create a tuple with one member like in (42) instead of (42,), because the braces are interpreted differently and you end up with a scalar instead.

Maybe we should explain whether this is a problem in Rust or not.

Before "channels", perhaps more on typing should be introduced

The "channels" chapter presents the following snippet:

fn main() {
    // channels have two endpoints: the Sender<T> and the Receiver<T>,
    // where T is the type of the message to be transfer
    // (type annotation is superfluous)
    let (tx, rx): (Sender<_>, Receiver<_>) = channel();

I find that it's not entirely clear that

  • _ can also be used a placeholder in the type. It seems to not have been mentioned before.
  • The exact type of _ is inferred based on expressions after the let. I have learned of H-M and it seems rust implements it, but it could be confusing to someone only familiar with local inference.

These two points seem to be unmentioned (but should be) before this chapter. Correct me if I have missed them out. Although I managed to figure those out, it could still be confusing to others :)

Typo: 21. Global Constants

In Section 21, one of the comments has a minor typo:

// when static_string goes out of scope, we can't no longer refer

should read:

// when static_string goes out of scope, we can no longer refer

Travis CI

Using travis to verify any pull requests and all commits would make collaboration on the website much easier

Embed a playpen-like editor inside the book

I got this working [1][2] in the editor branch and have setup a clone site for testing.

At the moment, I have two bugs to fix:

  • The buttons are misplaced, they should be inside the editor area
  • You need to refresh the page to see the editor
  • Use the same colors when highlighting both static code and the code inside the editor.
  • Height of the editor should always fit the contained source code.

I'll like to have other people test it, and let me know if you have any suggestion or if you find any other bug. (or if you know how to fix any of the bugs I have mentioned :P - here's the css and the js if you want to take a look)

Once we are sure the editor works the way we want, I'll merge this into the original site.

[1] I've reused @SergioBenitez live code editor implementation for the rust-lang.org website. Kudos to him!
[2] Implementation detail: The "{hello.play}" string in the input markdown gets expanded into the live code editor containing the hello.rs source code

cc @kud1ing @vojtechkral @vks @zslayton


Original description

The playpen exposes a CORS-enabled JSON API that could be used to embed a playpen-like editor in each example, this would allow the user to run the example, and see the output inline; or experiment further by editing the source code of the example.

See rust-lang/prev.rust-lang.org#26 for a reference implementation. We should try to provide a similar interface to the one provided by rust-lang.org (plus a "Reset" button to show the original example code)

In "bounds", maybe explain the relationship of + and Add::add

The code sample has used both of them. Here the .add method from Add trait:

// The Add<T, U> trait overloads the + operator: (Self + T = U)
impl<
    // bound: T implements the Add trait
    T: Add<T, T>
> Add<Vec2<T>, Vec2<T>>
for Vec2<T> {
    // add() is a required method of the Add trait
    fn add(&self, rhs: &Vec2<T>) -> Vec2<T> {
        Vec2 {
            // x and y are of type T, and implement the add() method
            x: self.x.add(&rhs.x),
            y: self.x.add(&rhs.y),
        }
    }
}

and here the + operator:

fn main() {
    let v1 = Vec2 { x: 1.0, y: 2.0 };
    let v2 = Vec2 { x: 2.0, y: 1.0 };

    println!("{} + {} = {}", v1, v2, v1 + v2);
    println!("{} - {} = {}", v1, v2, v1 - v2);
    println!("{} . {} = {}", v1, v2, v1.dot(&v2));
}

It would be helpful to explain the relationship between the two; I suppose + is just a shorthand for the method call?

Moving/ownership & exceptions needs some work

http://rustbyexample.com/examples/move/README.html

The exception to these move semantics are the primitives types like int, uint, f64, etc, which are copied instead of moved since they are small in size.

Firstly, the reason given is not true: ~T is the same size as uint but the former moves & the latter "copies".

Under the hood a "move" is memcpy-ing the raw bytes of a type (e.g. moving a (u8, u8) duplicates those two bytes, and moving a ~uint duplicates the 8 bytes (or 4) bytes of the pointer). However, some types have ownership over resources and are responsible for cleaning them up (for example, a ~ owns the allocation, and needs to free it), hence just duplicating their bytes willy-nilly is highly likely to be semantically incorrect (you can't safely have two ~s that are the same pointer). One could imagine a rule where the compiler assumes every type has some ownership (let's just work with this for a bit...).

Thus, if you write let y = x;, you shouldn't be allowed to continue to use x, because the information (& ownership) has be transfered to y. This is a move: the compiler statically disallows using x, in other words, when you use a type by-value, any further uses of the source are statically disallowed.

However, the rule of assuming everything has some resources (i.e. that everything has to move) is overly general. There are some types which clearly have no resources, like primitives int, or things composed only of primitives like

struct Foo { x: int, y: Bar, z: () }

enum Bar { Baz(char, (bool, u8), Qux) }

struct Qux;

For these types, copying the raw bytes is semantically a copy, i.e. there's no allocations that need duplicating, or reference counts that need to be adjusted. Hence, the compiler understands that when use such a type by-value e.g. let y = x; the source doesn't need to be invalidated, i.e. the compiler lets you continue using x.

This behaviour is captured by the Copy kind, that is, you can continue to reuse the source of a by-value use of a type if and only if the type implements the Copy kind (there's no easy way to actually check if some type implements that kind other than by just trying to reuse the source, unfortunately, but work is being to make this easier to reason about).

(I'm writing this up because I really think that this ownership concept is one of the most important concepts in Rust, and understanding it will make later things (like lifetimes & references) much easier to understand.)


Appendix: What I mean by "by-value use" is things like

// some value
let x: T = ...;

// use x by-value, to put it into y
let y = x;

// pass y by-value to the function
foo(y)

fn foo(arg: T) ->T { 
    // pass arg by-value to the caller
    return arg;
}

This is the converse to by-reference, i.e. let y = &x; or foo(&x) etc.

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.