From 035cfcbe7218018c1bab29a987ee1152ccd1dcf7 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 6 Oct 2012 15:47:57 -0700 Subject: docs: Clean up trait and module examples --- doc/tutorial.md | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index bf262105f6e..1b857bae1eb 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -2044,13 +2044,11 @@ However, consider this function: # type Circle = int; type Rectangle = int; # impl int: Drawable { fn draw() {} } # fn new_circle() -> int { 1 } - trait Drawable { fn draw(); } fn draw_all(shapes: ~[T]) { for shapes.each |shape| { shape.draw(); } } - # let c: Circle = new_circle(); # draw_all(~[c]); ~~~~ @@ -2062,7 +2060,7 @@ needed, a trait name can alternately be used as a type. ~~~~ # trait Drawable { fn draw(); } -fn draw_all(shapes: ~[@Drawable]) { +fn draw_all(shapes: &[@Drawable]) { for shapes.each |shape| { shape.draw(); } } ~~~~ @@ -2077,7 +2075,7 @@ to cast a value to a trait type: # trait Drawable { fn draw(); } # fn new_circle() -> Circle { 1 } # fn new_rectangle() -> Rectangle { true } -# fn draw_all(shapes: ~[Drawable]) {} +# fn draw_all(shapes: &[@Drawable]) {} impl @Circle: Drawable { fn draw() { ... } } @@ -2085,7 +2083,7 @@ impl @Rectangle: Drawable { fn draw() { ... } } let c: @Circle = @new_circle(); let r: @Rectangle = @new_rectangle(); -draw_all(~[c as @Drawable, r as @Drawable]); +draw_all(&[c as @Drawable, r as @Drawable]); ~~~~ Note that, like strings and vectors, trait types have dynamic size @@ -2130,10 +2128,9 @@ explicitly import it, you must refer to it by its long name, `farm::chicken`. ~~~~ -#[legacy_exports] mod farm { - fn chicken() -> ~str { ~"cluck cluck" } - fn cow() -> ~str { ~"mooo" } + pub fn chicken() -> ~str { ~"cluck cluck" } + pub fn cow() -> ~str { ~"mooo" } } fn main() { io::println(farm::chicken()); -- cgit 1.4.1-3-g733a5 From f5c95de212d7851c7f8788a328455ed381e38978 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 6 Oct 2012 20:23:38 -0700 Subject: docs: Edit the into bullets --- doc/tutorial.md | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index 1b857bae1eb..37b0b722eaa 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -15,21 +15,17 @@ As a multi-paradigm language, Rust supports writing code in procedural, functional and object-oriented styles. Some of its pleasant high-level features include: -* **Pattern matching and algebraic data types (enums).** As - popularized by functional languages, pattern matching on ADTs - provides a compact and expressive way to encode program logic. -* **Type inference.** Type annotations on local variable - declarations are optional. -* **Task-based concurrency.** Rust uses lightweight tasks that do - not share memory. -* **Higher-order functions.** Rust's efficient and flexible closures - are heavily relied on to provide iteration and other control - structures -* **Parametric polymorphism (generics).** Functions and types can be - parameterized over type variables with optional trait-based type - constraints. -* **Trait polymorphism.** Rust's type system features a unique - combination of type classes and object-oriented interfaces. +* **Type inference.** Type annotations on local variable declarations + are optional. +* **Safe task-based concurrency.** Rust's lightweight tasks do not share + memory and communicate through messages. +* **Higher-order functions.** Efficient and flexible closures provide + iteration and other control structures +* **Pattern matching and algebraic data types.** Pattern matching on + Rust's enums is a compact and expressive way to encode program + logic. +* **Polymorphism.** Rust has type-parameric functions and + types, type classes and OO-style interfaces. ## Scope -- cgit 1.4.1-3-g733a5 From d5d774124730ee363620c6e4ec5bf65deea2385c Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 6 Oct 2012 22:23:16 -0700 Subject: Overhaul mods and crates section of tutorial --- doc/lib/codemirror-rust.js | 2 +- doc/tutorial.md | 315 ++++++++++++++++++++++----------------------- 2 files changed, 154 insertions(+), 163 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/lib/codemirror-rust.js b/doc/lib/codemirror-rust.js index 02f2c603955..727882d3099 100644 --- a/doc/lib/codemirror-rust.js +++ b/doc/lib/codemirror-rust.js @@ -9,7 +9,7 @@ CodeMirror.defineMode("rust", function() { "as": "op", "true": "atom", "false": "atom", "assert": "op", "check": "op", "claim": "op", "extern": "ignore", "unsafe": "ignore", "import": "else-style", "export": "else-style", "copy": "op", "log": "op", - "use": "op", "self": "atom" + "use": "op", "self": "atom", "pub": "atom", "priv": "atom" }; var typeKeywords = function() { var keywords = {"fn": "fn"}; diff --git a/doc/tutorial.md b/doc/tutorial.md index 37b0b722eaa..f73ddd1b4c4 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -31,7 +31,7 @@ pleasant high-level features include: This is an introductory tutorial for the Rust programming language. It covers the fundamentals of the language, including the syntax, the -type system and memory model, and generics. [Additional +type system and memory model, generics, and modules. [Additional tutorials](#what-next) cover specific language features in greater depth. @@ -2113,61 +2113,123 @@ This usage of traits is similar to Java interfaces. # Modules and crates -The Rust namespace is divided into modules. Each source file starts -with its own module. - -## Local modules - -The `mod` keyword can be used to open a new, local module. In the -example below, `chicken` lives in the module `farm`, so, unless you -explicitly import it, you must refer to it by its long name, -`farm::chicken`. +The Rust namespace is arranged in a hierarchy of modules. Each source +(.rs) file represents a single module and may in turn contain +additional modules. ~~~~ mod farm { pub fn chicken() -> ~str { ~"cluck cluck" } pub fn cow() -> ~str { ~"mooo" } } + fn main() { io::println(farm::chicken()); } ~~~~ -Modules can be nested to arbitrary depth. +The contents of modules can be imported into the current scope +with the `use` keyword, optionally giving it an alias. `use` +may appear at the beginning of crates, `mod`s, `fn`s, and other +blocks. + +~~~ +# mod farm { pub fn chicken() { } } +# fn main() { +// Bring `chicken` into scope +use farm::chicken; + +fn chicken_farmer() { + // The same, but name it `my_chicken` + use my_chicken = farm::chicken; + ... +} +# } +~~~ + +These farm animal functions have a new keyword, `pub`, attached to +them. This is a visibility modifier that allows item to be accessed +outside of the module in which they are declared, using `::`, as in +`farm::chicken`. Items, like `fn`, `struct`, etc. are private by +default. + +Visibility restrictions in Rust exist only at module boundaries. This +is quite different from most object-oriented languages that also enforce +restrictions on objects themselves. That's not to say that Rust doesn't +support encapsulation - both struct fields and methods can be private - +but it is at the module level, not the class level. Note that fields +and methods are _public_ by default. + +~~~ +mod farm { +# pub fn make_me_a_farm() -> farm::Farm { farm::Farm { chickens: ~[], cows: ~[], farmer: Human(0) } } + pub struct Farm { + priv mut chickens: ~[Chicken], + priv mut cows: ~[Cow], + farmer: Human + } + + // Note - visibility modifiers on impls currently have no effect + impl Farm { + priv fn feed_chickens() { ... } + priv fn feed_cows() { ... } + fn add_chicken(c: Chicken) { ... } + } + + pub fn feed_animals(farm: &Farm) { + farm.feed_chickens(); + farm.feed_cows(); + } +} + +fn main() { + let f = make_me_a_farm(); + f.add_chicken(make_me_a_chicken()); + farm::feed_animals(&f); + f.farmer.rest(); +} +# type Chicken = int; +# type Cow = int; +# enum Human = int; +# fn make_me_a_farm() -> farm::Farm { farm::make_me_a_farm() } +# fn make_me_a_chicken() -> Chicken { 0 } +# impl Human { fn rest() { } } +~~~ ## Crates -The unit of independent compilation in Rust is the crate. Libraries -tend to be packaged as crates, and your own programs may consist of -one or more crates. +The unit of independent compilation in Rust is the crate - rustc +compiles a single crate at a time, from which it produces either a +library or executable. When compiling a single `.rs` file, the file acts as the whole crate. You can compile it with the `--lib` compiler switch to create a shared library, or without, provided that your file contains a `fn main` somewhere, to create an executable. -It is also possible to include multiple files in a crate. For this -purpose, you create a `.rc` crate file, which references any number of -`.rs` code files. A crate file could look like this: +Larger crates typically span multiple files and are compiled from +a crate (.rc) file. Crate files contain their own syntax for loading +modules from .rs files and typically include metadata about the crate. -~~~~ {.ignore} +~~~~ { .xfail-test } #[link(name = "farm", vers = "2.5", author = "mjh")]; #[crate_type = "lib"]; + mod cow; mod chicken; mod horse; ~~~~ Compiling this file will cause `rustc` to look for files named -`cow.rs`, `chicken.rs`, `horse.rs` in the same directory as the `.rc` -file, compile them all together, and, depending on the presence of the -`crate_type = "lib"` attribute, output a shared library or an executable. -(If the line `#[crate_type = "lib"];` was omitted, `rustc` would create an -executable.) +`cow.rs`, `chicken.rs`, and `horse.rs` in the same directory as the +`.rc` file, compile them all together, and, based on the presence of +the `crate_type = "lib"` attribute, output a shared library or an +executable. (If the line `#[crate_type = "lib"];` was omitted, +`rustc` would create an executable.) -The `#[link(...)]` part provides meta information about the module, -which other crates can use to load the right module. More about that -later. +The `#[link(...)]` attribute provides meta information about the +module, which other crates can use to load the right module. More +about that later. To have a nested directory structure for your source files, you can nest mods in your `.rc` file: @@ -2184,56 +2246,65 @@ The compiler will now look for `poultry/chicken.rs` and and `poultry::turkey`. You can also provide a `poultry.rs` to add content to the `poultry` module itself. -The compiler then builds the crate as a platform-specific shared library or -executable which can be distributed. +When compiling .rc files, if rustc finds a .rs file with the same +name, then that .rs file provides the top-level content of the crate. -## Using other crates +~~~ {.xfail-test} +// foo.rc +#[link(name = "foo", vers="1.0")]; -Having compiled a crate that contains the `#[crate_type = "lib"]` -attribute, you can use it in another crate with a `use` -directive. We've already seen `extern mod std` in several of the -examples, which loads in the [standard library][std]. +mod bar; +~~~ -[std]: http://doc.rust-lang.org/doc/std/index/General.html +~~~ {.xfail-test} +// foo.rs +fn main() { bar::baz(); } +~~~ -`use` directives can appear in a crate file, or at the top level of a -single-file `.rs` crate. They will cause the compiler to search its -library search path (which you can extend with `-L` switch) for a Rust -crate library with the right name. +> ***Note***: The way rustc looks for .rs files to pair with .rc +> files is a major source of confusion and will change. It's likely +> that the crate and source file grammars will merge. -It is possible to provide more specific information when using an -external crate. +> ***Note***: The way that directory modules are handled will also +> change. The code for directory modules currently lives in a .rs +> file with the same name as the directory, _next to_ the directory. +> A new scheme will make that file live _inside_ the directory. -~~~~ {.ignore} -extern mod myfarm (name = "farm", vers = "2.7"); -~~~~ +## Using other crates + +Having compiled a crate into a library you can use it in another crate +with an `extern mod` directive. `extern mod` can appear at the top of +a crate file or at the top of modules. It will cause the compiler to +look in the library search path (which you can extend with `-L` +switch) for a compiled Rust library with the right name, then add a +module with that crate's name into the local scope. -When a comma-separated list of name/value pairs is given after `use`, -these are matched against the attributes provided in the `link` +For example, `extern mod std` links the [standard library]. + +[standard library]: std/index.html + +When a comma-separated list of name/value pairs is given after `extern +mod`, these are matched against the attributes provided in the `link` attribute of the crate file, and a crate is only used when the two match. A `name` value can be given to override the name used to search -for the crate. So the above would import the `farm` crate under the -local name `myfarm`. +for the crate. Our example crate declared this set of `link` attributes: -~~~~ {.ignore} +~~~~ {.xfail-test} #[link(name = "farm", vers = "2.5", author = "mjh")]; ~~~~ -The version does not match the one provided in the `use` directive, so -unless the compiler can find another crate with the right version -somewhere, it will complain that no matching crate was found. - -## The core library +Which can then be linked with any (or all) of the following: -A set of basic library routines, mostly related to built-in datatypes -and the task system, are always implicitly linked and included in any -Rust program. +~~~~ {.xfail-test} +extern mod farm; +extern mod my_farm (name = "farm", vers = "2.5"); +extern mod my_auxiliary_farm (name = "farm", author = "mjh"); +~~~~ -This library is documented [here][core]. - -[core]: core/index.html +If any of the requested metadata does not match then the crate +will not be compiled successfully. ## A minimal example @@ -2246,7 +2317,7 @@ these two files: fn explore() -> ~str { ~"world" } ~~~~ -~~~~ {.ignore} +~~~~ {.xfail-test} // main.rs extern mod world; fn main() { io::println(~"hello " + world::explore()); } @@ -2261,113 +2332,33 @@ Now compile and run like this (adjust to your platform if necessary): "hello world" ~~~~ -## Importing - -When using identifiers from other modules, it can get tiresome to -qualify them with the full module path every time (especially when -that path is several modules deep). Rust allows you to import -identifiers at the top of a file, module, or block. - -~~~~ -extern mod std; -use io::println; -fn main() { - println(~"that was easy"); -} -~~~~ - - -It is also possible to import just the name of a module (`use -std::list;`, then use `list::find`), to import all identifiers exported -by a given module (`use io::*`), or to import a specific set -of identifiers (`use math::{min, max, pi}`). - -Rust uses different namespaces for modules, types, and values. You -can also rename an identifier when importing using the `=` operator: - -~~~~ -use prnt = io::println; -~~~~ - -## Exporting - -By default, a module exports everything that it defines. This can be -restricted with `export` directives at the top of the module or file. - -~~~~ -mod enc { - export encrypt, decrypt; - const SUPER_SECRET_NUMBER: int = 10; - fn encrypt(n: int) -> int { n + SUPER_SECRET_NUMBER } - fn decrypt(n: int) -> int { n - SUPER_SECRET_NUMBER } -} -~~~~ - -This defines a rock-solid encryption algorithm. Code outside of the -module can refer to the `enc::encrypt` and `enc::decrypt` identifiers -just fine, but it does not have access to `enc::super_secret_number`. - -## Resolution - -The resolution process in Rust simply goes up the chain of contexts, -looking for the name in each context. Nested functions and modules -create new contexts inside their parent function or module. A file -that's part of a bigger crate will have that crate's context as its -parent context. - -Identifiers can shadow each other. In this program, `x` is of type -`int`: +Notice that the library produced contains the version in the filename +as well as an inscrutable string of alphanumerics. These are both +part of Rust's library versioning scheme. The alphanumerics are +a hash representing the crate metadata. -~~~~ -type MyType = ~str; -fn main() { - type MyType = int; - let x: MyType = 17; -} -~~~~ - -An `use` directive will only import into the namespaces for which -identifiers are actually found. Consider this example: - -~~~~ -mod foo { - fn bar() {} -} - -fn main() { - let bar = 10; - - { - use foo::bar; - let quux = bar; - assert quux == 10; - } -} -~~~~ +## The core library -When resolving the type name `bar` in the `quux` definition, the -resolver will first look at local block context for `baz`. This has an -import named `bar`, but that's function, not a value, So it continues -to the `baz` function context and finds a value named `bar` defined -there. +The Rust [core] library acts as the language runtime and contains +required memory management and task scheduling code as well as a +number of modules necessary for effective usage of the primitive +types. Methods on [vectors] and [strings], implementations of most +comparison and math operators, and pervasive types like [`Option`] +and [`Result`] live in core. -Normally, multiple definitions of the same identifier in a scope are -disallowed. Local variables defined with `let` are an exception to -this—multiple `let` directives can redefine the same variable in a -single scope. When resolving the name of such a variable, the most -recent definition is used. +All Rust programs link to the core library and import its contents, +as if the following were written at the top of the crate. -~~~~ -fn main() { - let x = 10; - let x = x + 10; - assert x == 20; -} -~~~~ +~~~ {.xfail-test} +extern mod core; +use core::*; +~~~ -This makes it possible to rebind a variable without actually mutating -it, which is mostly useful for destructuring (which can rebind, but -not assign). +[core]: core/index.html +[vectors]: core/vec.html +[strings]: core/str.html +[`Option`]: core/option.html +[`Result`]: core/result.html # What next? -- cgit 1.4.1-3-g733a5 From 0b2ffa5692ce83bbf499262e6023c8f7673f0522 Mon Sep 17 00:00:00 2001 From: Jacob Harris Cryer Kragh Date: Sat, 6 Oct 2012 11:56:29 +0300 Subject: tutorial: Add missing struct name --- doc/tutorial.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index f73ddd1b4c4..0badbb8c05d 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -879,10 +879,10 @@ parentheses. # enum Direction { North, East, South, West } fn point_from_direction(dir: Direction) -> Point { match dir { - North => {x: 0f, y: 1f}, - East => {x: 1f, y: 0f}, - South => {x: 0f, y: -1f}, - West => {x: -1f, y: 0f} + North => Point {x: 0f, y: 1f}, + East => Point {x: 1f, y: 0f}, + South => Point {x: 0f, y: -1f}, + West => Point {x: -1f, y: 0f} } } ~~~~ -- cgit 1.4.1-3-g733a5 From ba26dc50cecb66e10e183dc834fb570979a475b7 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 6 Oct 2012 22:35:08 -0700 Subject: docs: Remove more uses of records --- doc/tutorial.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index 0badbb8c05d..78a7b5e5f25 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -859,12 +859,12 @@ get at their contents. All variant constructors can be used as patterns, as in this definition of `area`: ~~~~ -# type Point = {x: float, y: float}; +# struct Point {x: float, y: float} # enum Shape { Circle(Point, float), Rectangle(Point, Point) } fn area(sh: Shape) -> float { match sh { Circle(_, size) => float::consts::pi * size * size, - Rectangle({x, y}, {x: x2, y: y2}) => (x2 - x) * (y2 - y) + Rectangle(Point {x, y}, Point {x: x2, y: y2}) => (x2 - x) * (y2 - y) } } ~~~~ @@ -875,7 +875,7 @@ their introductory form, nullary enum patterns are written without parentheses. ~~~~ -# type Point = {x: float, y: float}; +# struct Point {x: float, y: float} # enum Direction { North, East, South, West } fn point_from_direction(dir: Direction) -> Point { match dir { -- cgit 1.4.1-3-g733a5 From fe5526f49c824b73b00dd8f43bf9b6f97aa2a9a0 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 6 Oct 2012 22:40:12 -0700 Subject: docs: Fix capitalization of section title --- doc/tutorial.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index 78a7b5e5f25..1dac6468fdc 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -179,7 +179,7 @@ mode for your favorite editor, let us know so that we can link to it. [sublime]: http://github.com/dbp/sublime-rust [sublime-pkg]: http://wbond.net/sublime_packages/package_control -# Syntax Basics +# Syntax basics Assuming you've programmed in any C-family language (C++, Java, JavaScript, C#, or PHP), Rust will feel familiar. Code is arranged -- cgit 1.4.1-3-g733a5 From b6443519c8b325bd554e8ea7283b02ebe1632e8f Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 6 Oct 2012 22:45:48 -0700 Subject: Remove some redundant info from tutorial --- doc/tutorial.md | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index 1dac6468fdc..e64de6134d7 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -686,19 +686,7 @@ For more involved iteration, such as going over the elements of a collection, Rust uses higher-order functions. We'll come back to those in a moment. -# Basic datatypes - -The core datatypes of Rust are structs, enums (tagged unions, algebraic data -types), and tuples. They are immutable by default. - -~~~~ -struct Point { x: float, y: float } - -enum Shape { - Circle(Point, float), - Rectangle(Point, Point) -} -~~~~ +# Data structures ## Structs -- cgit 1.4.1-3-g733a5 From c6330036a4e20a60f7ade12ed9f4d53b8fc9d762 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 6 Oct 2012 22:47:26 -0700 Subject: 'The' Rust Language Tutorial --- doc/tutorial.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index e64de6134d7..33b66d0a1cd 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1,4 +1,4 @@ -% Rust Language Tutorial +% The Rust Language Tutorial # Introduction -- cgit 1.4.1-3-g733a5 From f0c4140dd09555e274e472a0d14fd22bbef579d8 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 6 Oct 2012 22:57:40 -0700 Subject: More tutorial tweaking --- doc/tutorial.md | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index 33b66d0a1cd..c06c9b54772 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -128,19 +128,7 @@ fn main() { If the Rust compiler was installed successfully, running `rustc hello.rs` will produce an executable called `hello` (or `hello.exe` on -Windows) which, upon running, will likely do exactly what you expect -(unless you are on Windows, in which case what it does is subject -to local weather conditions). - -> ***Note:*** That may or may not be hyperbole, but there are some -> 'gotchas' to be aware of on Windows. First, the MinGW environment -> must be set up perfectly. Please read [the -> wiki][wiki-started]. Second, `rustc` may need to be [referred to as -> `rustc.exe`][bug-3319]. It's a bummer, I know, and I am so very -> sorry. - -[bug-3319]: https://github.com/mozilla/rust/issues/3319 -[wiki-started]: https://github.com/mozilla/rust/wiki/Note-getting-started-developing-Rust +Windows) which, upon running, will likely do exactly what you expect. The Rust compiler tries to provide useful information when it runs into an error. If you modify the program to make it invalid (for @@ -160,6 +148,15 @@ declaration to appear at the top level of the file—all statements must live inside a function. Rust programs can also be compiled as libraries, and included in other programs. +> ***Note:*** There are some 'gotchas' to be aware of on +> Windows. First, the MinGW environment must be set up +> perfectly. Please read [the wiki][wiki-started]. Second, `rustc` may +> need to be [referred to as `rustc.exe`][bug-3319]. It's a bummer, I +> know. + +[bug-3319]: https://github.com/mozilla/rust/issues/3319 +[wiki-started]: https://github.com/mozilla/rust/wiki/Note-getting-started-developing-Rust + ## Editing Rust code There are vim highlighting and indentation scripts in the Rust source -- cgit 1.4.1-3-g733a5 From 07fb35227b08d35213a7a17cded9a3933fd09479 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 7 Oct 2012 01:06:07 -0700 Subject: Tutorial --- doc/tutorial.md | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index c06c9b54772..dc7dec766ef 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1335,13 +1335,12 @@ stored on the stack, the local heap, or the exchange heap. Borrowed pointers to vectors are also called 'slices'. ~~~ -enum Crayon { - Almond, AntiqueBrass, Apricot, - Aquamarine, Asparagus, AtomicTangerine, - BananaMania, Beaver, Bittersweet, - Black, BlizzardBlue, Blue -} - +# enum Crayon { +# Almond, AntiqueBrass, Apricot, +# Aquamarine, Asparagus, AtomicTangerine, +# BananaMania, Beaver, Bittersweet, +# Black, BlizzardBlue, Blue +# } // A fixed-size stack vector let stack_crayons: [Crayon * 3] = [Almond, AntiqueBrass, Apricot]; @@ -1368,8 +1367,7 @@ let your_crayons = ~[BananaMania, Beaver, Bittersweet]; // Add two vectors to create a new one let our_crayons = my_crayons + your_crayons; -// += will append to a vector, provided it leves -// in a mutable slot +// += will append to a vector, provided it lives in a mutable slot let mut my_crayons = move my_crayons; my_crayons += your_crayons; ~~~~ -- cgit 1.4.1-3-g733a5 From 2a41abb9efee7e07b3989f3a60b994a05c386851 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 7 Oct 2012 01:52:06 -0700 Subject: Work on the tutorial section on 'do' --- doc/tutorial.md | 45 ++++++++++++++++++++++----------------------- 1 file changed, 22 insertions(+), 23 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index dc7dec766ef..36b118a21a3 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1618,10 +1618,8 @@ call_twice(bare_function); ## Do syntax -The `do` expression is syntactic sugar for use with functions which -take a closure as a final argument, because closures in Rust -are so frequently used in combination with higher-order -functions. +The `do` expression provides a way to treat higher-order functions +(functions that take closures as arguments) as control structures. Consider this function which iterates over a vector of integers, passing in a pointer to each integer in the vector: @@ -1636,20 +1634,22 @@ fn each(v: &[int], op: fn(v: &int)) { } ~~~~ -The reason we pass in a *pointer* to an integer rather than the -integer itself is that this is how the actual `each()` function for -vectors works. Using a pointer means that the function can be used -for vectors of any type, even large structs that would be impractical -to copy out of the vector on each iteration. As a caller, if we use a -closure to provide the final operator argument, we can write it in a -way that has a pleasant, block-like structure. +As an aside, the reason we pass in a *pointer* to an integer rather +than the integer itself is that this is how the actual `each()` +function for vectors works. `vec::each` though is a +[generic](#generics) function, so must be efficient to use for all +types. Passing the elements by pointer avoids copying potentially +large objects. + +As a caller, if we use a closure to provide the final operator +argument, we can write it in a way that has a pleasant, block-like +structure. ~~~~ # fn each(v: &[int], op: fn(v: &int)) { } -# fn do_some_work(i: int) { } +# fn do_some_work(i: &int) { } each(&[1, 2, 3], |n| { - debug!("%i", *n); - do_some_work(*n); + do_some_work(n); }); ~~~~ @@ -1658,10 +1658,9 @@ call that can be written more like a built-in control structure: ~~~~ # fn each(v: &[int], op: fn(v: &int)) { } -# fn do_some_work(i: int) { } +# fn do_some_work(i: &int) { } do each(&[1, 2, 3]) |n| { - debug!("%i", *n); - do_some_work(*n); + do_some_work(n); } ~~~~ @@ -1670,7 +1669,9 @@ final closure inside the argument list it is moved outside of the parenthesis where it looks visually more like a typical block of code. -`do` is often used for task spawning. +`do` is often used to create tasks with the `task::spawn` function. +`spawn` has the signature `spawn(fn: fn~())`. In other words, it +is a function that takes an owned closure that takes no arguments. ~~~~ use task::spawn; @@ -1680,9 +1681,9 @@ do spawn() || { } ~~~~ -That's nice, but look at all those bars and parentheses - that's two empty -argument lists back to back. Wouldn't it be great if they weren't -there? +Look at all those bars and parentheses - that's two empty argument +lists back to back. Since that is so unsightly, empty argument lists +may be omitted from `do` expressions. ~~~~ # use task::spawn; @@ -1691,8 +1692,6 @@ do spawn { } ~~~~ -Empty argument lists can be omitted from `do` expressions. - ## For loops Most iteration in Rust is done with `for` loops. Like `do`, -- cgit 1.4.1-3-g733a5 From 4c968f47e0df71d78c4c02f1e8fa008be70661c7 Mon Sep 17 00:00:00 2001 From: tav Date: Tue, 9 Oct 2012 01:24:54 +0100 Subject: doc: Remove duplicate word typo in the tutorial. --- doc/tutorial.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index 36b118a21a3..d49fcf92cab 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -965,7 +965,7 @@ s.draw(); ~~~ This defines an _implementation_ for `Shape` containing a single -method, `draw`. In most most respects the `draw` method is defined +method, `draw`. In most respects the `draw` method is defined like any other function, with the exception of the name `self`. `self` is a special value that is automatically defined in each method, referring to the value being operated on. If we wanted we could add -- cgit 1.4.1-3-g733a5 From 6da09c3b437dad240218b91ea06c301982764152 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Tue, 9 Oct 2012 21:21:07 -0700 Subject: doc: Fix some inaccuracies in the tutorial. * Pointers can refer to stack objects as well as heap objects. * Non-managed types can be cyclic if an arena is used. --- doc/tutorial.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index d49fcf92cab..dc88b2a8911 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1054,7 +1054,7 @@ copied, not just a pointer. For small structs like `Point`, this is usually more efficient than allocating memory and going through a pointer. But for big structs, or those with mutable fields, it can be useful to have a single copy on -the heap, and refer to that through a pointer. +the stack or on the heap, and refer to that through a pointer. Rust supports several types of pointers. The safe pointer types are `@T` for managed boxes allocated on the local heap, `~T`, for @@ -1087,8 +1087,7 @@ let y = x; // Copy of a pointer to the same box ~~~~ Any type that contains managed boxes or other managed types is -considered _managed_. Managed types are the only types that can -construct cyclic data structures in Rust, such as doubly-linked lists. +considered _managed_. ~~~ // A linked list node -- cgit 1.4.1-3-g733a5 From d9317a174e434d4c99fc1a37fd7dc0d2f5328d37 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Tue, 9 Oct 2012 21:39:18 -0700 Subject: doc: Tweak the wording of the memory model goals --- doc/tutorial.md | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index dc88b2a8911..59117d339a1 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -988,16 +988,17 @@ illuminate several of Rust's unique features as we encounter them. Rust has three competing goals that inform its view of memory: -* Memory safety: memory that is managed by and is accessible to the - Rust language must be guaranteed to be valid; under normal +* Memory safety: Memory that is managed by and is accessible to the + Rust language must be guaranteed to be valid. Under normal circumstances it must be impossible for Rust to trigger a - segmentation fault or leak memory -* Performance: high-performance low-level code must be able to employ - a number of allocation strategies; low-performance high-level code - must be able to employ a single, garbage-collection-based, heap - allocation strategy -* Concurrency: Rust must maintain memory safety guarantees, even for - code running in parallel + segmentation fault or leak memory. +* Performance: High-performance low-level code must be able to employ + a number of allocation strategies. Tracing garbage collection must be + optional and, if it is not desired, memory safety must not be compromised. + Less performance-critical, high-level code should be able to employ a single, + garbage-collection-based, heap allocation strategy. +* Concurrency: Rust code must be free of in-memory data races. (Note that other + types of races are still possible.) ## How performance considerations influence the memory model -- cgit 1.4.1-3-g733a5 From b7b22179761a71df4ec77185b54f134601130592 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Wed, 10 Oct 2012 17:56:23 -0700 Subject: Update tutorial install instructions --- doc/tutorial.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index 59117d339a1..e01e50a9394 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -71,7 +71,7 @@ Snapshot binaries are currently built and tested on several platforms: * Windows (7, Server 2008 R2), x86 only * Linux (various distributions), x86 and x86-64 -* OSX 10.6 ("Snow Leopard") or 10.7 ("Lion"), x86 and x86-64 +* OSX 10.6 ("Snow Leopard") or greater, x86 and x86-64 You may find that other platforms work, but these are our "tier 1" supported build environments that are most likely to work. @@ -79,7 +79,7 @@ supported build environments that are most likely to work. > ***Note:*** Windows users should read the detailed > [getting started][wiki-start] notes on the wiki. Even when using > the binary installer the Windows build requires a MinGW installation, -> the precise details of which are not discussed in this tutorial. +> the precise details of which are not discussed here. To build from source you will also need the following prerequisite packages: -- cgit 1.4.1-3-g733a5 From 38ccaed4ce0892bfa36c210302c42de1aa4dd584 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Wed, 10 Oct 2012 19:05:13 -0700 Subject: Copyedit sections 1 and 2 of tutorial --- doc/tutorial.md | 61 +++++++++++++++++++++++++++------------------------------ 1 file changed, 29 insertions(+), 32 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index e01e50a9394..0ff22927176 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -4,7 +4,7 @@ Rust is a programming language with a focus on type safety, memory safety, concurrency and performance. It is intended for writing -large-scale, high-performance software while preventing several +large-scale, high-performance software that is free from several classes of common errors. Rust has a sophisticated memory model that encourages efficient data structures and safe concurrency patterns, forbidding invalid memory accesses that would otherwise cause @@ -18,13 +18,14 @@ pleasant high-level features include: * **Type inference.** Type annotations on local variable declarations are optional. * **Safe task-based concurrency.** Rust's lightweight tasks do not share - memory and communicate through messages. + memory, instead communicating through messages. * **Higher-order functions.** Efficient and flexible closures provide iteration and other control structures * **Pattern matching and algebraic data types.** Pattern matching on - Rust's enums is a compact and expressive way to encode program - logic. -* **Polymorphism.** Rust has type-parameric functions and + Rust's enumeration types (a more powerful version of C's enums, + similar to algebraic data types in functional languages) is a + compact and expressive way to encode program logic. +* **Polymorphism.** Rust has type-parametric functions and types, type classes and OO-style interfaces. ## Scope @@ -35,23 +36,23 @@ type system and memory model, generics, and modules. [Additional tutorials](#what-next) cover specific language features in greater depth. -It assumes the reader is familiar with the basic concepts of +This tutorial assumes that the reader is familiar with the basic concepts of programming, and has programmed in one or more other languages -before. It will often make comparisons to other languages, +before. We will often compare Rust to other languages, particularly those in the C family. ## Conventions -Throughout the tutorial, words that indicate language keywords or -identifiers defined in example code are displayed in `code font`. +Throughout the tutorial, language keywords and identifiers defined in +example code are displayed in `code font`. Code snippets are indented, and also shown in a monospaced font. Not all snippets constitute whole programs. For brevity, we'll often show fragments of programs that don't compile on their own. To try them out, you might have to wrap them in `fn main() { ... }`, and make sure -they don't contain references to things that aren't actually defined. +they don't contain references to names that aren't actually defined. -> ***Warning:*** Rust is a language under heavy development. Notes +> ***Warning:*** Rust is a language under ongoing development. Notes > about potential changes to the language, implementation > deficiencies, and other caveats appear offset in blockquotes. @@ -77,9 +78,14 @@ You may find that other platforms work, but these are our "tier 1" supported build environments that are most likely to work. > ***Note:*** Windows users should read the detailed -> [getting started][wiki-start] notes on the wiki. Even when using -> the binary installer the Windows build requires a MinGW installation, -> the precise details of which are not discussed here. +> "[getting started][wiki-start]" notes on the wiki. Even when using +> the binary installer, the Windows build requires a MinGW installation, +> the precise details of which are not discussed here. Finally, `rustc` may +> need to be [referred to as `rustc.exe`][bug-3319]. It's a bummer, I +> know. + +[bug-3319]: https://github.com/mozilla/rust/issues/3319 +[wiki-start]: https://github.com/mozilla/rust/wiki/Note-getting-started-developing-Rust To build from source you will also need the following prerequisite packages: @@ -90,8 +96,8 @@ packages: * gnu make 3.81 or later * curl -Assuming you're on a relatively modern *nix system and have met the -prerequisites, something along these lines should work. +If you've fulfilled those prerequisites, something along these lines +should work. ~~~~ {.notrust} $ wget http://dl.rust-lang.org/dist/rust-0.4.tar.gz @@ -104,7 +110,7 @@ $ make && make install You may need to use `sudo make install` if you do not normally have permission to modify the destination directory. The install locations can be adjusted by passing a `--prefix` argument to -`configure`. Various other options are also supported, pass `--help` +`configure`. Various other options are also supported: pass `--help` for more information on them. When complete, `make install` will place several programs into @@ -130,10 +136,10 @@ If the Rust compiler was installed successfully, running `rustc hello.rs` will produce an executable called `hello` (or `hello.exe` on Windows) which, upon running, will likely do exactly what you expect. -The Rust compiler tries to provide useful information when it runs -into an error. If you modify the program to make it invalid (for -example, by changing `io::println` to some nonexistent function), and -then compile it, you'll see an error message like this: +The Rust compiler tries to provide useful information when it encounters an +error. If you introduce an error into the program (for example, by changing +`io::println` to some nonexistent function), and then compile it, you'll see +an error message like this: ~~~~ {.notrust} hello.rs:2:4: 2:16 error: unresolved name: io::print_with_unicorns @@ -144,19 +150,10 @@ hello.rs:2 io::print_with_unicorns("hello? yes, this is rust"); In its simplest form, a Rust program is a `.rs` file with some types and functions defined in it. If it has a `main` function, it can be compiled to an executable. Rust does not allow code that's not a -declaration to appear at the top level of the file—all statements must +declaration to appear at the top level of the file: all statements must live inside a function. Rust programs can also be compiled as libraries, and included in other programs. -> ***Note:*** There are some 'gotchas' to be aware of on -> Windows. First, the MinGW environment must be set up -> perfectly. Please read [the wiki][wiki-started]. Second, `rustc` may -> need to be [referred to as `rustc.exe`][bug-3319]. It's a bummer, I -> know. - -[bug-3319]: https://github.com/mozilla/rust/issues/3319 -[wiki-started]: https://github.com/mozilla/rust/wiki/Note-getting-started-developing-Rust - ## Editing Rust code There are vim highlighting and indentation scripts in the Rust source @@ -170,7 +167,7 @@ Sublime Text 2, available both [standalone][sublime] and through under `src/etc/kate`. There is ctags support via `src/etc/ctags.rust`, but many other -tools and editors are not provided for yet. If you end up writing a Rust +tools and editors are not yet supported. If you end up writing a Rust mode for your favorite editor, let us know so that we can link to it. [sublime]: http://github.com/dbp/sublime-rust -- cgit 1.4.1-3-g733a5 From 6627ac662386541737ab26e3a1c633dc88185c62 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Wed, 10 Oct 2012 19:32:11 -0700 Subject: Copyedit section 3 of tutorial --- doc/tutorial.md | 98 +++++++++++++++++++++++++++++++-------------------------- 1 file changed, 53 insertions(+), 45 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index 0ff22927176..2d43d19deff 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -184,8 +184,8 @@ and mostly have the same precedence as in C; comments are again like C. The main surface difference to be aware of is that the condition at the head of control structures like `if` and `while` do not require -paretheses, while their bodies *must* be wrapped in -brackets. Single-statement, bracket-less bodies are not allowed. +parentheses, while their bodies *must* be wrapped in +braces. Single-statement, unbraced bodies are not allowed. ~~~~ # fn recalibrate_universe() -> bool { true } @@ -200,9 +200,9 @@ fn main() { } ~~~~ -The `let` keyword introduces a local variable. Variables are immutable -by default, so `let mut` can be used to introduce a local variable -that can be reassigned. +The `let` keyword introduces a local variable. Variables are immutable by +default. To introduce a local variable that you can re-assign later, use `let +mut` instead. ~~~~ let hi = "hi"; @@ -224,14 +224,14 @@ let imaginary_size = monster_size * 10.0; let monster_size: int = 50; ~~~~ -Local variables may shadow earlier declarations, as in the previous -example in which `monster_size` is first declared as a `float` -then a second `monster_size` is declared as an int. If you were to actually -compile this example though, the compiler will see that the second -`monster_size` is unused, assume that you have made a mistake, and issue -a warning. For occasions where unused variables are intentional, their -name may be prefixed with an underscore to silence the warning, like -`let _monster_size = 50;`. +Local variables may shadow earlier declarations, as in the previous example: +`monster_size` was first declared as a `float`, and then then a second +`monster_size` was declared as an int. If you were to actually compile this +example, though, the compiler will determine that the second `monster_size` is +unused and issue a warning (because this situation is likely to indicate a +programmer error). For occasions where unused variables are intentional, their +name may be prefixed with an underscore to silence the warning, like `let +_monster_size = 50;`. Rust identifiers follow the same rules as C; they start with an alphabetic character or an underscore, and after that may contain any sequence of @@ -278,10 +278,10 @@ let price = }; ~~~~ -Both pieces of code are exactly equivalent—they assign a value to +Both pieces of code are exactly equivalent: they assign a value to `price` depending on the condition that holds. Note that there -are not semicolons in the blocks of the second snippet. This is -important; the lack of a semicolon after the last statement in a +are no semicolons in the blocks of the second snippet. This is +important: the lack of a semicolon after the last statement in a braced block gives the whole block the value of that last expression. Put another way, the semicolon in Rust *ignores the value of an expression*. @@ -290,8 +290,10 @@ would simply assign `()` (nil or void) to `price`. But without the semicolon, ea branch has a different value, and `price` gets the value of the branch that was taken. -In short, everything that's not a declaration (`let` for variables, -`fn` for functions, et cetera) is an expression, including function bodies. +In short, everything that's not a declaration (declarations are `let` for +variables, `fn` for functions, and any top-level named items such as +[traits](#traits), [enum types](#enums), and [constants](#constants)) is an +expression, including function bodies. ~~~~ fn is_four(x: int) -> bool { @@ -314,7 +316,7 @@ something—in which case you'll have embedded it in a bigger statement. # fn foo() -> bool { true } # fn bar() -> bool { true } # fn baz() -> bool { true } -// `let` is not an expression, so it is semi-colon terminated; +// `let` is not an expression, so it is semicolon-terminated; let x = foo(); // When used in statement position, bracy expressions do not @@ -346,7 +348,7 @@ This may sound intricate, but it is super-useful and will grow on you. The basic types include the usual boolean, integral, and floating-point types. ------------------------- ----------------------------------------------- -`()` Nil, the type that has only a single value +`()` Unit, the type that has only a single value `bool` Boolean type, with values `true` and `false` `int`, `uint` Machine-pointer-sized signed and unsigned integers `i8`, `i16`, `i32`, `i64` Signed integers with a specific size (in bits) @@ -394,10 +396,15 @@ type MonsterSize = uint; This will provide a synonym, `MonsterSize`, for unsigned integers. It will not actually create a new, incompatible type—`MonsterSize` and `uint` can be used interchangeably, and using one where the other is expected is not a type -error. +error. In that sense, types declared with `type` are *structural*: their +meaning follows from their structure, and their names are irrelevant in the +type system. -To create data types which are not synonyms, `struct` and `enum` -can be used. They're described in more detail below, but they look like this: +Sometimes, you want your data types to be *nominal* instead of structural: you +want their name to be part of their meaning, so that types with the same +structure but different names are not interchangeable. Rust has two ways to +create nominal data types: `struct` and `enum`. They're described in more +detail below, but they look like this: ~~~~ enum HidingPlaces { @@ -416,12 +423,12 @@ enum MonsterSize = uint; // a single-variant enum ## Literals -Integers can be written in decimal (`144`), hexadecimal (`0x90`), and +Integers can be written in decimal (`144`), hexadecimal (`0x90`), or binary (`0b10010000`) base. Each integral type has a corresponding literal suffix that can be used to indicate the type of a literal: `i` for `int`, `u` for `uint`, and `i8` for the `i8` type, etc. -In the absense of an integer literal suffix, Rust will infer the +In the absence of an integer literal suffix, Rust will infer the integer type based on type annotations and function signatures in the surrounding program. In the absence of any type information at all, Rust will assume that an unsuffixed integer literal has type @@ -439,10 +446,10 @@ a suffix, the literal is assumed to be of type `float`. Suffixes `f32` (32-bit) and `f64` (64-bit) can be used to create literals of a specific type. -The nil literal is written just like the type: `()`. The keywords +The unit literal is written just like the type: `()`. The keywords `true` and `false` produce the boolean literals. -Character literals are written between single quotes, as in `'x'`. Just as in +Character literals are written between single quotes, as in `'x'`. Just like C, Rust understands a number of character escapes, using the backslash character, such as `\n`, `\r`, and `\t`. String literals, written between double quotes, allow the same escape sequences. Rust strings @@ -450,13 +457,13 @@ may contain newlines. ## Constants -Compile-time constants are declared with `const`. All scalar types, -like integers and floats, may be declared `const`, as well as fixed -length vectors, static strings (more on this later), and structs. -Constants may be declared in any scope and may refer to other -constants. Constant declarations are not type inferred, so must always -have a type annotation. By convention they are written in all capital -letters. +Compile-time constants are declared with `const`. A constant may have any +scalar type (for example, integer or float). Other allowable constant types +are fixed-length vectors, static strings (more on this later), and +structs. Constants may be declared in any scope and may refer to other +constants. The compiler does not infer types for constants, so constants must +always be declared with a type annotation. By convention, they are written in +all capital letters. ~~~ // Scalars can be constants @@ -480,7 +487,7 @@ const MY_STRUCTY_PASSWORD: Password = Password { value: MY_PASSWORD }; Rust's set of operators contains very few surprises. Arithmetic is done with `*`, `/`, `%`, `+`, and `-` (multiply, divide, remainder, plus, minus). `-` is -also a unary prefix operator that does negation. As in C, the bit operators +also a unary prefix operator that negates numbers. As in C, the bit operators `>>`, `<<`, `&`, `|`, and `^` are also supported. Note that, if applied to an integer value, `!` flips all the bits (like `~` in @@ -502,21 +509,21 @@ assert y == 4u; ~~~~ The main difference with C is that `++` and `--` are missing, and that -the logical bitwise operators have higher precedence — in C, `x & 2 > 0` +the logical bitwise operators have higher precedence—in C, `x & 2 > 0` means `x & (2 > 0)`, but in Rust, it means `(x & 2) > 0`, which is -more likely what a novice expects. +more likely to be what a novice expects. ## Syntax extensions *Syntax extensions* are special forms that are not built into the language, but are instead provided by the libraries. To make it clear to the reader when -a syntax extension is being used, the names of all syntax extensions end with -`!`. The standard library defines a few syntax extensions, the most useful of -which is `fmt!`, a `sprintf`-style text formatter that is expanded at compile -time. +a name refers to a syntax extension, the names of all syntax extensions end +with `!`. The standard library defines a few syntax extensions, the most +useful of which is `fmt!`, a `sprintf`-style text formatter that an early +compiler phase expands statically. -`fmt!` supports most of the directives that [printf][pf] supports, but -will give you a compile-time error when the types of the directives +`fmt!` supports most of the directives that [printf][pf] supports, but unlike +printf, will give you a compile-time error when the types of the directives don't match the types of the arguments. ~~~~ @@ -530,8 +537,9 @@ io::println(fmt!("what is this thing: %?", mystery_object)); [pf]: http://en.cppreference.com/w/cpp/io/c/fprintf -You can define your own syntax extensions with the macro system, which is out -of scope of this tutorial. +You can define your own syntax extensions with the macro system. For details, see the [macro tutorial][macros]. + +[macros]: tutorial-macros.html # Control structures -- cgit 1.4.1-3-g733a5 From d7b8512eae0f92e64b8a9eabe8584ac18bf9e061 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Wed, 10 Oct 2012 20:08:08 -0700 Subject: Copyedit section 4 of tutorial --- doc/tutorial.md | 91 +++++++++++++++++++++++++++++++-------------------------- 1 file changed, 49 insertions(+), 42 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index 2d43d19deff..1695977e627 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -545,8 +545,8 @@ You can define your own syntax extensions with the macro system. For details, se ## Conditionals -We've seen `if` pass by a few times already. To recap, braces are -compulsory, an optional `else` clause can be appended, and multiple +We've seen `if` expressions a few times already. To recap, braces are +compulsory, an `if` can have an optional `else` clause, and multiple `if`/`else` constructs can be chained together: ~~~~ @@ -559,10 +559,10 @@ if false { } ~~~~ -The condition given to an `if` construct *must* be of type boolean (no -implicit conversion happens). If the arms return a value, this value -must be of the same type for every arm in which control reaches the -end of the block: +The condition given to an `if` construct *must* be of type `bool` (no +implicit conversion happens). If the arms are blocks that have a +value, this value must be of the same type for every arm in which +control reaches the end of the block: ~~~~ fn signum(x: int) -> int { @@ -575,9 +575,10 @@ fn signum(x: int) -> int { ## Pattern matching Rust's `match` construct is a generalized, cleaned-up version of C's -`switch` construct. You provide it with a value and a number of *arms*, -each labelled with a pattern, and the code will attempt to match each pattern -in order. For the first one that matches, the arm is executed. +`switch` construct. You provide it with a value and a number of +*arms*, each labelled with a pattern, and the code compares the value +against each pattern in order until one matches. The matching pattern +executes its corresponding arm. ~~~~ # let my_number = 1; @@ -589,15 +590,19 @@ match my_number { } ~~~~ -There is no 'falling through' between arms, as in C—only one arm is -executed, and it doesn't have to explicitly `break` out of the +Unlike in C, there is no 'falling through' between arms: only one arm +executes, and it doesn't have to explicitly `break` out of the construct when it is finished. -The part to the left of the arrow `=>` is called the *pattern*. Literals are -valid patterns and will match only their own value. The pipe operator -(`|`) can be used to assign multiple patterns to a single arm. Ranges -of numeric literal patterns can be expressed with two dots, as in `M..N`. The -underscore (`_`) is a wildcard pattern that matches everything. +A `match` arm consists of a *pattern*, then an arrow `=>`, followed by +an *action* (expression). Literals are valid patterns and match only +their own value. A single arm may match multiple different patterns by +combining them with the pipe operator (`|`), so long as every pattern +binds the same set of variables. Ranges of numeric literal patterns +can be expressed with two dots, as in `M..N`. The underscore (`_`) is +a wildcard pattern that matches any single value. The asterisk (`*`) +is a different wildcard that can match one or more fields in an `enum` +variant. The patterns in an match arm are followed by a fat arrow, `=>`, then an expression to evaluate. Each case is separated by commas. It's often @@ -612,13 +617,14 @@ match my_number { } ~~~ -`match` constructs must be *exhaustive*: they must have an arm covering every -possible case. For example, if the arm with the wildcard pattern was left off -in the above example, the typechecker would reject it. +`match` constructs must be *exhaustive*: they must have an arm +covering every possible case. For example, the typechecker would +reject the previous example if the arm with the wildcard pattern was +omitted. -A powerful application of pattern matching is *destructuring*, where -you use the matching to get at the contents of data types. Remember -that `(float, float)` is a tuple of two floats: +A powerful application of pattern matching is *destructuring*: +matching in order to bind names to the contents of data +types. Remember that `(float, float)` is a tuple of two floats: ~~~~ fn angle(vector: (float, float)) -> float { @@ -631,37 +637,39 @@ fn angle(vector: (float, float)) -> float { } ~~~~ -A variable name in a pattern matches everything, *and* binds that name -to the value of the matched thing inside of the arm block. Thus, `(0f, +A variable name in a pattern matches any value, *and* binds that name +to the value of the matched value inside of the arm's action. Thus, `(0f, y)` matches any tuple whose first element is zero, and binds `y` to the second element. `(x, y)` matches any tuple, and binds both -elements to a variable. +elements to variables. -Any `match` arm can have a guard clause (written `if EXPR`), which is -an expression of type `bool` that determines, after the pattern is -found to match, whether the arm is taken or not. The variables bound -by the pattern are available in this guard expression. +Any `match` arm can have a guard clause (written `if EXPR`), called a +*pattern guard*, which is an expression of type `bool` that +determines, after the pattern is found to match, whether the arm is +taken or not. The variables bound by the pattern are in scope in this +guard expression. The first arm in the `angle` example shows an +example of a pattern guard. You've already seen simple `let` bindings, but `let` is a little -fancier than you've been led to believe. It too supports destructuring -patterns. For example, you can say this to extract the fields from a -tuple, introducing two variables, `a` and `b`. +fancier than you've been led to believe. It, too, supports destructuring +patterns. For example, you can write this to extract the fields from a +tuple, introducing two variables at once: `a` and `b`. ~~~~ # fn get_tuple_of_two_ints() -> (int, int) { (1, 1) } let (a, b) = get_tuple_of_two_ints(); ~~~~ -Let bindings only work with _irrefutable_ patterns, that is, patterns +Let bindings only work with _irrefutable_ patterns: that is, patterns that can never fail to match. This excludes `let` from matching -literals and most enum variants. +literals and most `enum` variants. ## Loops -`while` produces a loop that runs as long as its given condition -(which must have type `bool`) evaluates to true. Inside a loop, the -keyword `break` can be used to abort the loop, and `loop` can be used -to abort the current iteration and continue with the next. +`while` denotes a loop that iterates as long as its given condition +(which must have type `bool`) evaluates to `true`. Inside a loop, the +keyword `break` aborts the loop, and `loop` aborts the current +iteration and continues with the next. ~~~~ let mut cake_amount = 8; @@ -670,7 +678,7 @@ while cake_amount > 0 { } ~~~~ -`loop` is the preferred way of writing `while true`: +`loop` denotes an infinite loop, and is the preferred way of writing `while true`: ~~~~ let mut x = 5; @@ -684,9 +692,8 @@ loop { This code prints out a weird sequence of numbers and stops as soon as it finds one that can be divided by five. -For more involved iteration, such as going over the elements of a -collection, Rust uses higher-order functions. We'll come back to those -in a moment. +For more involved iteration, such as enumerating the elements of a +collection, Rust uses [higher-order functions](#closures). # Data structures -- cgit 1.4.1-3-g733a5 From 1a8b00a03a45c19a47165ce037ae703e4e71f202 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Wed, 10 Oct 2012 20:35:33 -0700 Subject: Copyedit sections 5 and 6 of the tutorial --- doc/tutorial.md | 110 +++++++++++++++++++++++++++++++++----------------------- 1 file changed, 65 insertions(+), 45 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index 1695977e627..e784a08801f 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -702,11 +702,11 @@ collection, Rust uses [higher-order functions](#closures). Rust struct types must be declared before they are used using the `struct` syntax: `struct Name { field1: T1, field2: T2 [, ...] }`, where `T1`, `T2`, ... denote types. To construct a struct, use the same syntax, but leave off -the `struct`; for example: `Point { x: 1.0, y: 2.0 }`. +the `struct`: for example: `Point { x: 1.0, y: 2.0 }`. Structs are quite similar to C structs and are even laid out the same way in -memory (so you can read from a Rust struct in C, and vice-versa). The dot -operator is used to access struct fields (`mypoint.x`). +memory (so you can read from a Rust struct in C, and vice-versa). Use the dot +operator to access struct fields, as in `mypoint.x`. Fields that you want to mutate must be explicitly marked `mut`. @@ -720,7 +720,7 @@ struct Stack { With a value of such a type, you can do `mystack.head += 1`. If `mut` were omitted from the type, such an assignment would result in a type error. -Structs can be destructured in `match` patterns. The basic syntax is +`match` patterns destructure structs. The basic syntax is `Name {fieldname: pattern, ...}`: ~~~~ @@ -747,9 +747,9 @@ match mypoint { } ~~~ -Structs are the only type in Rust that may have user-defined destructors, -using `drop` blocks, inside of which the struct's value may be referred -to with the name `self`. +Structs are the only type in Rust that may have user-defined +destructors, defined with `drop` blocks. Inside a `drop`, the name +`self` refers to the struct's value. ~~~ struct TimeBomb { @@ -783,16 +783,16 @@ A value of this type is either a `Circle`, in which case it contains a `Point` struct and a float, or a `Rectangle`, in which case it contains two `Point` structs. The run-time representation of such a value includes an identifier of the actual form that it holds, much like the -'tagged union' pattern in C, but with better ergonomics. +'tagged union' pattern in C, but with better static guarantees. -The above declaration will define a type `Shape` that can be used to -refer to such shapes, and two functions, `Circle` and `Rectangle`, -which can be used to construct values of the type (taking arguments of -the specified types). So `Circle(Point {x: 0f, y: 0f}, 10f)` is the way to +The above declaration will define a type `Shape` that can refer to +such shapes, and two functions, `Circle` and `Rectangle`, which can be +used to construct values of the type (taking arguments of the +specified types). So `Circle(Point {x: 0f, y: 0f}, 10f)` is the way to create a new circle. -Enum variants need not have type parameters. This, for example, is -equivalent to a C enum: +Enum variants need not have type parameters. This `enum` declaration, +for example, is equivalent to a C enum: ~~~~ enum Direction { @@ -803,12 +803,12 @@ enum Direction { } ~~~~ -This will define `North`, `East`, `South`, and `West` as constants, +This declaration defines `North`, `East`, `South`, and `West` as constants, all of which have type `Direction`. -When an enum is C-like, that is, when none of the variants have -parameters, it is possible to explicitly set the discriminator values -to an integer value: +When an enum is C-like (that is, when none of the variants have +parameters), it is possible to explicitly set the discriminator values +to a constant value: ~~~~ enum Color { @@ -821,16 +821,19 @@ enum Color { If an explicit discriminator is not specified for a variant, the value defaults to the value of the previous variant plus one. If the first variant does not have a discriminator, it defaults to 0. For example, -the value of `North` is 0, `East` is 1, etc. +the value of `North` is 0, `East` is 1, `South` is 2, and `West` is 3. -When an enum is C-like the `as` cast operator can be used to get the -discriminator's value. +When an enum is C-like, you can apply the `as` cast operator to +convert it to its discriminator value as an int. -There is a special case for enums with a single variant. These are -used to define new types in such a way that the new name is not just a -synonym for an existing type, but its own distinct type. If you say: +There is a special case for enums with a single variant, which are +sometimes called "newtype-style enums" (after Haskell's "newtype" +feature). These are used to define new types in such a way that the +new name is not just a synonym for an existing type, but its own +distinct type: `type` creates a structural synonym, while this form of +`enum` creates a nominal synonym. If you say: ~~~~ enum GizmoId = int; @@ -842,7 +845,7 @@ That is a shorthand for this: enum GizmoId { GizmoId(int) } ~~~~ -Enum types like this can have their content extracted with the +You can extract the contents of such an enum type with the dereference (`*`) unary operator: ~~~~ @@ -851,6 +854,17 @@ let my_gizmo_id: GizmoId = GizmoId(10); let id_int: int = *my_gizmo_id; ~~~~ +Types like this can be useful to differentiate between data that have +the same type but must be used in different ways. + +~~~~ +enum Inches = int; +enum Centimeters = int; +~~~~ + +The above definitions allow for a simple way for programs to avoid +confusing numbers that correspond to different units. + For enum types with multiple variants, destructuring is the only way to get at their contents. All variant constructors can be used as patterns, as in this definition of `area`: @@ -866,9 +880,9 @@ fn area(sh: Shape) -> float { } ~~~~ -Like other patterns, a lone underscore ignores individual fields. -Ignoring all fields of a variant can be written `Circle(*)`. As in -their introductory form, nullary enum patterns are written without +You can write a lone `_` to ignore an individual fields, and can +ignore all fields of a variant like: `Circle(*)`. As in their +introduction form, nullary enum patterns are written without parentheses. ~~~~ @@ -887,9 +901,9 @@ fn point_from_direction(dir: Direction) -> Point { ## Tuples Tuples in Rust behave exactly like structs, except that their fields -do not have names (and can thus not be accessed with dot notation). +do not have names. Thus, you cannot access their fields with dot notation. Tuples can have any arity except for 0 or 1 (though you may consider -nil, `()`, as the empty tuple if you like). +unit, `()`, as the empty tuple if you like). ~~~~ let mytup: (int, int, float) = (10, 20, 30.0); @@ -902,10 +916,11 @@ match mytup { We've already seen several function definitions. Like all other static declarations, such as `type`, functions can be declared both at the -top level and inside other functions (or modules, which we'll come -back to [later](#modules-and-crates)). They are introduced with the -`fn` keyword, the type of arguments are specified following colons and -the return type follows the arrow. +top level and inside other functions (or in modules, which we'll come +back to [later](#modules-and-crates)). The `fn` keyword introduces a +function. A function has an argument list, which is a parenthesized +list of `expr: type` pairs separated by commas. An arrow `->` +separates the argument list and the function's return type. ~~~~ fn line(a: int, b: int, x: int) -> int { @@ -924,9 +939,12 @@ fn line(a: int, b: int, x: int) -> int { } ~~~~ -Functions that do not return a value are said to return nil, `()`, -and both the return type and the return value may be omitted from -the definition. The following two functions are equivalent. +It's better Rust style to write a return value this way instead of +writing an explicit `return`. The utility of `return` comes in when +returning early from a function. Functions that do not return a value +are said to return nil, `()`, and both the return type and the return +value may be omitted from the definition. The following two functions +are equivalent. ~~~~ fn do_nothing_the_hard_way() -> () { return (); } @@ -944,10 +962,12 @@ assert 8 == line(5, 3, 1); assert () == oops(5, 3, 1); ~~~~ -Methods are like functions, except that they are defined for a specific -'self' type (like 'this' in C++). Calling a method is done with -dot notation, as in `my_vec.len()`. Methods may be defined on most -Rust types with the `impl` keyword. As an example, lets define a draw +Methods are like functions, except that they have an implicit argument +called `self`, which has the type that the method's receiver has. The +`self` argument is like 'this' in C++. An expression with dot +notation, as in `my_vec.len()`, denotes a method +call. Implementations, written with the `impl` keyword, can define +methods on most Rust types. As an example, let's define a `draw` method on our `Shape` enum. ~~~ @@ -978,15 +998,15 @@ s.draw(); This defines an _implementation_ for `Shape` containing a single method, `draw`. In most respects the `draw` method is defined -like any other function, with the exception of the name `self`. `self` -is a special value that is automatically defined in each method, +like any other function, except for the name `self`. `self` +is a special value that is automatically in scope inside each method, referring to the value being operated on. If we wanted we could add additional methods to the same impl, or multiple impls for the same type. We'll discuss methods more in the context of [traits and generics](#generics). -> ***Note:*** The method definition syntax will change to require -> declaring the self type explicitly, as the first argument. +> ***Note:*** In the future, the method definition syntax will change to +> require declaring the `self` type explicitly, as the first argument. # The Rust memory model -- cgit 1.4.1-3-g733a5 From 7582a482c68ab641764d39a0c3428d9b7ce39603 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Wed, 10 Oct 2012 20:52:20 -0700 Subject: Copyedit sections 7 and 8 of the tutorial --- doc/tutorial.md | 145 +++++++++++++++++++++++++++++--------------------------- 1 file changed, 75 insertions(+), 70 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index e784a08801f..01ca36f9e9b 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1010,22 +1010,22 @@ generics](#generics). # The Rust memory model -At this junction let's take a detour to explain the concepts involved +At this junction, let's take a detour to explain the concepts involved in Rust's memory model. We've seen some of Rust's pointer sigils (`@`, `~`, and `&`) float by in a few examples, and we aren't going to get much further without explaining them. Rust has a very particular approach to memory management that plays a significant role in shaping -the "feel" of the language. Understanding the memory landscape will -illuminate several of Rust's unique features as we encounter them. +the subjective experience of programming in the +language. Understanding the memory landscape will illuminate several +of Rust's unique features as we encounter them. Rust has three competing goals that inform its view of memory: -* Memory safety: Memory that is managed by and is accessible to the - Rust language must be guaranteed to be valid. Under normal - circumstances it must be impossible for Rust to trigger a - segmentation fault or leak memory. -* Performance: High-performance low-level code must be able to employ - a number of allocation strategies. Tracing garbage collection must be +* Memory safety: Memory that the Rust language can observe must be + guaranteed to be valid. Under normal circumstances, it must be + impossible for Rust to trigger a segmentation fault or leak memory. +* Performance: High-performance low-level code must be able to use + a number of different allocation strategies. Tracing garbage collection must be optional and, if it is not desired, memory safety must not be compromised. Less performance-critical, high-level code should be able to employ a single, garbage-collection-based, heap allocation strategy. @@ -1034,7 +1034,7 @@ Rust has three competing goals that inform its view of memory: ## How performance considerations influence the memory model -Most languages that offer strong memory safety guarantees rely upon a +Most languages that offer strong memory safety guarantees rely on a garbage-collected heap to manage all of the objects. This approach is straightforward both in concept and in implementation, but has significant costs. Languages that follow this path tend to @@ -1044,18 +1044,20 @@ boxes_: memory allocated on the heap whose lifetime is managed by the garbage collector. By comparison, languages like C++ offer very precise control over -where objects are allocated. In particular, it is common to put them +where objects are allocated. In particular, it is common to allocate them directly on the stack, avoiding expensive heap allocation. In Rust -this is possible as well, and the compiler will use a clever _pointer -lifetime analysis_ to ensure that no variable can refer to stack +this is possible as well, and the compiler uses a [clever _pointer +lifetime analysis_][borrow] to ensure that no variable can refer to stack objects after they are destroyed. +[borrow]: tutorial-borrowed-ptr.html + ## How concurrency considerations influence the memory model Memory safety in a concurrent environment involves avoiding race conditions between two threads of execution accessing the same -memory. Even high-level languages often require programmers to -correctly employ locking to ensure that a program is free of races. +memory. Even high-level languages often require programmers to make +correct use of locking to ensure that a program is free of races. Rust starts from the position that memory cannot be shared between tasks. Experience in other languages has proven that isolating each @@ -1064,28 +1066,30 @@ easy for programmers to reason about. Heap isolation has the additional benefit that garbage collection must only be done per-heap. Rust never "stops the world" to reclaim memory. -Complete isolation of heaps between tasks would, however, mean that any data -transferred between tasks must be copied. While this is a fine and -useful way to implement communication between tasks, it is also very -inefficient for large data structures. Because of this, Rust also -employs a global _exchange heap_. Objects allocated in the exchange -heap have _ownership semantics_, meaning that there is only a single -variable that refers to them. For this reason, they are referred to as -_owned boxes_. All tasks may allocate objects on the exchange heap, -then transfer ownership of those objects to other tasks, avoiding -expensive copies. +Complete isolation of heaps between tasks would, however, mean that +any data transferred between tasks must be copied. While this is a +fine and useful way to implement communication between tasks, it is +also very inefficient for large data structures. To reduce the amount +of copying, Rust also uses a global _exchange heap_. Objects allocated +in the exchange heap have _ownership semantics_, meaning that there is +only a single variable that refers to them. For this reason, they are +referred to as _owned boxes_. All tasks may allocate objects on the +exchange heap, then transfer ownership of those objects to other +tasks, avoiding expensive copies. # Boxes and pointers -In contrast to a lot of modern languages, aggregate types like structs -and enums are _not_ represented as pointers to allocated memory in -Rust. They are, as in C and C++, represented directly. This means that -if you `let x = Point {x: 1f, y: 1f};`, you are creating a struct on the -stack. If you then copy it into a data structure, the whole struct is -copied, not just a pointer. +Many modern languages have a so-called "uniform representation" for +aggregate types like structs and enums, so as to represent these types +as pointers to heap memory by default. In contrast, Rust, like C and +C++, represents such types directly. Another way to say this is that +aggregate data in Rust are *unboxed*. This means that if you `let x = +Point {x: 1f, y: 1f};`, you are creating a struct on the stack. If you +then copy it into a data structure, you copy the entire struct, not +just a pointer. For small structs like `Point`, this is usually more efficient than -allocating memory and going through a pointer. But for big structs, or +allocating memory and indirecting through a pointer. But for big structs, or those with mutable fields, it can be useful to have a single copy on the stack or on the heap, and refer to that through a pointer. @@ -1100,16 +1104,15 @@ All pointer types can be dereferenced with the `*` unary operator. > ***Note***: You may also hear managed boxes referred to as 'shared > boxes' or 'shared pointers', and owned boxes as 'unique boxes/pointers'. > Borrowed pointers are sometimes called 'region pointers'. The preferred -> terminology is as presented here. +> terminology is what we present here. ## Managed boxes -Managed boxes are pointers to heap-allocated, garbage collected memory. -Creating a managed box is done by simply applying the unary `@` -operator to an expression. The result of the expression will be boxed, -resulting in a box of the right type. Copying a shared box, as happens -during assignment, only copies a pointer, never the contents of the -box. +Managed boxes are pointers to heap-allocated, garbage collected +memory. Applying the unary `@` operator to an expression creates a +managed box. The resulting box contains the result of the +expression. Copying a shared box, as happens during assignment, only +copies a pointer, never the contents of the box. ~~~~ let x: @int = @10; // New box @@ -1119,8 +1122,8 @@ let y = x; // Copy of a pointer to the same box // then the allocation will be freed. ~~~~ -Any type that contains managed boxes or other managed types is -considered _managed_. +A _managed_ type is either of the form `@T` for some type `T`, or any +type that contains managed boxes or other managed types. ~~~ // A linked list node @@ -1148,19 +1151,19 @@ node3.prev = SomeNode(node2); Managed boxes never cross task boundaries. -> ***Note:*** managed boxes are currently reclaimed through reference -> counting and cycle collection, but we will switch to a tracing -> garbage collector eventually. +> ***Note:*** Currently, the Rust compiler generates code to reclaim +> managed boxes through reference counting and a cycle collector, but +> we will switch to a tracing garbage collector eventually. ## Owned boxes -In contrast to managed boxes, owned boxes have a single owning memory -slot and thus two owned boxes may not refer to the same memory. All -owned boxes across all tasks are allocated on a single _exchange -heap_, where their uniquely owned nature allows them to be passed -between tasks efficiently. +In contrast with managed boxes, owned boxes have a single owning +memory slot and thus two owned boxes may not refer to the same +memory. All owned boxes across all tasks are allocated on a single +_exchange heap_, where their uniquely owned nature allows tasks to +exchange them efficiently. -Because owned boxes are uniquely owned, copying them involves allocating +Because owned boxes are uniquely owned, copying them requires allocating a new owned box and duplicating the contents. Copying owned boxes is expensive so the compiler will complain if you do so without writing the word `copy`. @@ -1180,11 +1183,11 @@ let z = *x + *y; assert z == 20; ~~~~ -This is where the 'move' operator comes in. It is similar to -`copy`, but it de-initializes its source. Thus, the owned box can move -from `x` to `y`, without violating the constraint that it only has a -single owner (if you used assignment instead of the move operator, the -box would, in principle, be copied). +This is where the 'move' operator comes in. It is similar to `copy`, +but it de-initializes its source. Thus, the owned box can move from +`x` to `y`, without violating the constraint that it only has a single +owner (using assignment instead of the move operator would, in +principle, copy the box). ~~~~ {.xfail-test} let x = ~10; @@ -1198,16 +1201,16 @@ to other tasks. The sending task will give up ownership of the box, and won't be able to access it afterwards. The receiving task will become the sole owner of the box. -> ***Note:*** this discussion of copying vs moving does not account +> ***Note:*** This discussion of copying vs. moving does not account > for the "last use" rules that automatically promote copy operations -> to moves. Last use is expected to be removed from the language in +> to moves. We plan to remove last use from the language in > favor of explicit moves. ## Borrowed pointers Rust borrowed pointers are a general purpose reference/pointer type, similar to the C++ reference type, but guaranteed to point to valid -memory. In contrast to owned pointers, where the holder of a unique +memory. In contrast with owned pointers, where the holder of a unique pointer is the owner of the pointed-to memory, borrowed pointers never imply ownership. Pointers may be borrowed from any type, in which case the pointer is guaranteed not to outlive the value it points to. @@ -1220,9 +1223,9 @@ struct Point { } ~~~~ -We can use this simple definition to allocate points in many ways. For -example, in this code, each of these three local variables contains a -point, but allocated in a different place: +We can use this simple definition to allocate points in many different +ways. For example, in this code, each of these three local variables +contains a point, but allocated in a different location: ~~~ # struct Point { x: float, y: float } @@ -1306,7 +1309,8 @@ let sum = *managed + *owned + *borrowed; ~~~ Dereferenced mutable pointers may appear on the left hand side of -assignments, in which case the value they point to is modified. +assignments. Such an assignment modifies the value that the pointer +points to. ~~~ let managed = @mut 10; @@ -1321,8 +1325,8 @@ let borrowed = &mut value; ~~~ Pointers have high operator precedence, but lower precedence than the -dot operator used for field and method access. This can lead to some -awkward code filled with parenthesis. +dot operator used for field and method access. This precedence order +can sometimes make code awkward and parenthesis-filled. ~~~ # struct Point { x: float, y: float } @@ -1334,9 +1338,9 @@ let rect = &Rectangle(*start, *end); let area = (*rect).area(); ~~~ -To combat this ugliness the dot operator performs _automatic pointer -dereferencing_ on the receiver (the value on the left hand side of the -dot), so in most cases dereferencing the receiver is not necessary. +To combat this ugliness the dot operator applies _automatic pointer +dereferencing_ to the receiver (the value on the left hand side of the +dot), so in most cases, explicitly dereferencing the receiver is not necessary. ~~~ # struct Point { x: float, y: float } @@ -1348,8 +1352,9 @@ let rect = &Rectangle(*start, *end); let area = rect.area(); ~~~ -Auto-dereferencing is performed through any number of pointers. If you -felt inclined you could write something silly like +You can write an expression that dereferences any number of pointers +automatically. For example, if you felt inclined, you could write +something silly like ~~~ # struct Point { x: float, y: float } @@ -1357,7 +1362,7 @@ let point = &@~Point { x: 10f, y: 20f }; io::println(fmt!("%f", point.x)); ~~~ -The indexing operator (`[]`) is also auto-dereferencing. +The indexing operator (`[]`) also auto-dereferences. # Vectors and strings -- cgit 1.4.1-3-g733a5 From 6d250517edc9823b39f6e239ec03d19a18b577bd Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Wed, 10 Oct 2012 21:06:22 -0700 Subject: Copyedit sections 9 and 10 of the tutorial --- doc/tutorial.md | 93 +++++++++++++++++++++++++++++---------------------------- 1 file changed, 48 insertions(+), 45 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index 01ca36f9e9b..1103ba112a2 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1366,7 +1366,7 @@ The indexing operator (`[]`) also auto-dereferences. # Vectors and strings -Vectors are a contiguous section of memory containing zero or more +A vector is a contiguous section of memory containing zero or more values of the same type. Like other types in Rust, vectors can be stored on the stack, the local heap, or the exchange heap. Borrowed pointers to vectors are also called 'slices'. @@ -1411,10 +1411,10 @@ my_crayons += your_crayons; > ***Note:*** The above examples of vector addition use owned > vectors. Some operations on slices and stack vectors are -> not well supported yet, owned vectors are often the most +> not yet well-supported. Owned vectors are often the most > usable. -Indexing into vectors is done with square brackets: +Square brackets denote indexing into a vector: ~~~~ # enum Crayon { Almond, AntiqueBrass, Apricot, @@ -1429,7 +1429,7 @@ match crayons[0] { ~~~~ The elements of a vector _inherit the mutability of the vector_, -and as such individual elements may not be reassigned when the +and as such, individual elements may not be reassigned when the vector lives in an immutable slot. ~~~ {.xfail-test} @@ -1459,13 +1459,13 @@ mutable_crayons[0] = Apricot; This is a simple example of Rust's _dual-mode data structures_, also referred to as _freezing and thawing_. -Strings are implemented with vectors of `u8`, though they have a distinct -type. They support most of the same allocation options as -vectors, though the string literal without a storage sigil, e.g. -`"foo"` is treated differently than a comparable vector (`[foo]`). -Whereas plain vectors are stack-allocated fixed-length vectors, -plain strings are region pointers to read-only memory. Strings -are always immutable. +Strings are implemented with vectors of `u8`, though they have a +distinct type. They support most of the same allocation options as +vectors, though the string literal without a storage sigil (for +example, `"foo"`) is treated differently than a comparable vector +(`[foo]`). Whereas plain vectors are stack-allocated fixed-length +vectors, plain strings are region pointers to read-only +memory. All strings are immutable. ~~~ // A plain string is a slice to read-only (static) memory @@ -1528,8 +1528,9 @@ if favorite_crayon_name.len() > 5 { # Closures Named functions, like those we've seen so far, may not refer to local -variables declared outside the function - they do not "close over -their environment". For example, you couldn't write the following: +variables declared outside the function: they do not close over their +environment (sometimes referred to as "capturing" variables in their +environment). For example, you couldn't write the following: ~~~~ {.ignore} let foo = 10; @@ -1552,10 +1553,10 @@ let closure = |arg| println(fmt!("captured_var=%d, arg=%d", captured_var, arg)); call_closure_with_ten(closure); ~~~~ -Closures begin with the argument list between bars and are followed by +Closures begin with the argument list between vertical bars and are followed by a single expression. The types of the arguments are generally omitted, as is the return type, because the compiler can almost always infer -them. In the rare case where the compiler needs assistance though, the +them. In the rare case where the compiler needs assistance, though, the arguments and return types may be annotated. ~~~~ @@ -1575,9 +1576,10 @@ let mut max = 0; Stack closures are very efficient because their environment is allocated on the call stack and refers by pointer to captured locals. To ensure that stack closures never outlive the local -variables to which they refer, they can only be used in argument -position and cannot be stored in structures nor returned from -functions. Despite the limitations stack closures are used +variables to which they refer, stack closures are not +first-class. That is, they can only be used in argument position; they +cannot be stored in data structures or returned from +functions. Despite these limitations, stack closures are used pervasively in Rust code. ## Managed closures @@ -1586,12 +1588,12 @@ When you need to store a closure in a data structure, a stack closure will not do, since the compiler will refuse to let you store it. For this purpose, Rust provides a type of closure that has an arbitrary lifetime, written `fn@` (boxed closure, analogous to the `@` pointer -type described earlier). +type described earlier). This type of closure *is* first-class. A managed closure does not directly access its environment, but merely copies out the values that it closes over into a private data structure. This means that it can not assign to these variables, and -will not 'see' updates to them. +cannot observe updates to them. This code creates a closure that adds a given string to its argument, returns it from a function, and then calls it: @@ -1608,12 +1610,12 @@ fn main() { } ~~~~ -This example uses the long closure syntax, `fn@(s: ~str) ...`, -making the fact that we are declaring a box closure explicit. In -practice boxed closures are usually defined with the short closure -syntax introduced earlier, in which case the compiler will infer -the type of closure. Thus our managed closure example could also -be written: +This example uses the long closure syntax, `fn@(s: ~str) ...`. Using +this syntax makes it explicit that we are declaring a boxed +closure. In practice, boxed closures are usually defined with the +short closure syntax introduced earlier, in which case the compiler +infers the type of closure. Thus our managed closure example could +also be written: ~~~~ fn mk_appender(suffix: ~str) -> fn@(~str) -> ~str { @@ -1626,18 +1628,18 @@ fn mk_appender(suffix: ~str) -> fn@(~str) -> ~str { Owned closures, written `fn~` in analogy to the `~` pointer type, hold on to things that can safely be sent between processes. They copy the values they close over, much like managed -closures, but they also 'own' them—meaning no other code can access +closures, but they also own them: that is, no other code can access them. Owned closures are used in concurrent code, particularly for spawning [tasks](#tasks). ## Closure compatibility -A nice property of Rust closures is that you can pass any kind of +Rust closures have a convenient subtyping property: you can pass any kind of closure (as long as the arguments and return types match) to functions that expect a `fn()`. Thus, when writing a higher-order function that -wants to do nothing with its function argument beyond calling it, you -should almost always specify the type of that argument as `fn()`, so -that callers have the flexibility to pass whatever they want. +only calls its function argument, and does nothing else with it, you +should almost always declare the type of that argument as `fn()`. That way, +callers may pass any kind of closure. ~~~~ fn call_twice(f: fn()) { f(); f(); } @@ -1650,7 +1652,7 @@ call_twice(bare_function); ~~~~ > ***Note:*** Both the syntax and the semantics will be changing -> in small ways. At the moment they can be unsound in multiple +> in small ways. At the moment they can be unsound in some > scenarios, particularly with non-copyable types. ## Do syntax @@ -1658,7 +1660,7 @@ call_twice(bare_function); The `do` expression provides a way to treat higher-order functions (functions that take closures as arguments) as control structures. -Consider this function which iterates over a vector of +Consider this function that iterates over a vector of integers, passing in a pointer to each integer in the vector: ~~~~ @@ -1702,13 +1704,14 @@ do each(&[1, 2, 3]) |n| { ~~~~ The call is prefixed with the keyword `do` and, instead of writing the -final closure inside the argument list it is moved outside of the -parenthesis where it looks visually more like a typical block of +final closure inside the argument list, it appears outside of the +parentheses, where it looks more like a typical block of code. -`do` is often used to create tasks with the `task::spawn` function. -`spawn` has the signature `spawn(fn: fn~())`. In other words, it -is a function that takes an owned closure that takes no arguments. +`do` is a convenient way to create tasks with the `task::spawn` +function. `spawn` has the signature `spawn(fn: fn~())`. In other +words, it is a function that takes an owned closure that takes no +arguments. ~~~~ use task::spawn; @@ -1731,10 +1734,10 @@ do spawn { ## For loops -Most iteration in Rust is done with `for` loops. Like `do`, -`for` is a nice syntax for doing control flow with closures. -Additionally, within a `for` loop, `break`, `loop`, and `return` -work just as they do with `while` and `loop`. +The most common way to express iteration in Rust is with a `for` +loop. Like `do`, `for` is a nice syntax for describing control flow +with closures. Additionally, within a `for` loop, `break`, `loop`, +and `return` work just as they do with `while` and `loop`. Consider again our `each` function, this time improved to break early when the iteratee returns `false`: @@ -1765,7 +1768,7 @@ each(&[2, 4, 8, 5, 16], |n| { ~~~~ With `for`, functions like `each` can be treated more -like builtin looping structures. When calling `each` +like built-in looping structures. When calling `each` in a `for` loop, instead of returning `false` to break out of the loop, you just write `break`. To skip ahead to the next iteration, write `loop`. @@ -1783,8 +1786,8 @@ for each(&[2, 4, 8, 5, 16]) |n| { As an added bonus, you can use the `return` keyword, which is not normally allowed in closures, in a block that appears as the body of a -`for` loop — this will cause a return to happen from the outer -function, not just the loop body. +`for` loop: the meaning of `return` in such a block is to return from +the enclosing function, not just the loop body. ~~~~ # use each = vec::each; -- cgit 1.4.1-3-g733a5 From 39acb06503bc387709b22c17c32cd58cd16b617a Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Wed, 10 Oct 2012 21:29:25 -0700 Subject: Copyedit sections 11-13 of the tutorial. That's all, folks! --- doc/tutorial.md | 188 +++++++++++++++++++++++++++++++------------------------- 1 file changed, 103 insertions(+), 85 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index 1103ba112a2..ae88cda8d8e 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1807,10 +1807,13 @@ fn contains(v: &[int], elt: int) -> bool { # Generics -Throughout this tutorial, we've been defining functions that act only on -specific data types. With type parameters we can also define functions whose -arguments represent generic types, and which can be invoked with a variety -of types. Consider a generic `map` function. +Throughout this tutorial, we've been defining functions that act only +on specific data types. With type parameters we can also define +functions whose arguments have generic types, and which can be invoked +with a variety of types. Consider a generic `map` function, which +takes a function `function` and a vector `vector` and returns a new +vector consisting of the result of applying `function` to each element +of `vector`: ~~~~ fn map(vector: &[T], function: fn(v: &T) -> U) -> ~[U] { @@ -1824,17 +1827,18 @@ fn map(vector: &[T], function: fn(v: &T) -> U) -> ~[U] { When defined with type parameters, as denoted by ``, this function can be applied to any type of vector, as long as the type of -`function`'s argument and the type of the vector's content agree with +`function`'s argument and the type of the vector's contents agree with each other. Inside a generic function, the names of the type parameters -(capitalized by convention) stand for opaque types. You can't look -inside them, but you can pass them around. Note that instances of -generic types are often passed by pointer. For example, the -parameter `function()` is supplied with a pointer to a value of type -`T` and not a value of type `T` itself. This ensures that the -function works with the broadest set of types possible, since some -types are expensive or illegal to copy and pass by value. +(capitalized by convention) stand for opaque types. All you can do +with instances of these types is pass them around: you can't apply any +operations to them or pattern-match on them. Note that instances of +generic types are often passed by pointer. For example, the parameter +`function()` is supplied with a pointer to a value of type `T` and not +a value of type `T` itself. This ensures that the function works with +the broadest set of types possible, since some types are expensive or +illegal to copy and pass by value. Generic `type`, `struct`, and `enum` declarations follow the same pattern: @@ -1852,15 +1856,16 @@ enum Maybe { } ~~~~ -These declarations produce valid types like `Set`, `Stack` -and `Maybe`. +These declarations can be instantiated to valid types like `Set`, +`Stack` and `Maybe`. -Generic functions in Rust are compiled to very efficient runtime code -through a process called _monomorphisation_. This is a fancy way of -saying that, for each generic function you call, the compiler -generates a specialized version that is optimized specifically for the -argument types. In this respect Rust's generics have similar -performance characteristics to C++ templates. +The Rust compiler compiles generic functions very efficiently by +*monomorphizing* them. *Monomorphization* is a fancy name for a simple +idea: generate a separate copy of each generic function at each call +site where it is called, a copy that is specialized to the argument +types and can thus be optimized specifically for them. In this +respect, Rust's generics have similar performance characteristics to +C++ templates. ## Traits @@ -1869,15 +1874,19 @@ are very limited. After all, since the function doesn't know what types it is operating on, it can't safely modify or query their values. This is where _traits_ come into play. Traits are Rust's most powerful tool for writing polymorphic code. Java developers will see -in them aspects of Java interfaces, and Haskellers will notice their -similarities to type classes. - -As motivation, let us consider copying in Rust. Perhaps surprisingly, -the copy operation is not defined for all Rust types. In -particular, types with user-defined destructors cannot be copied, -either implicitly or explicitly, and neither can types that own other -types containing destructors (the actual mechanism for defining -destructors will be discussed elsewhere). +them as similar to Java interfaces, and Haskellers will notice their +similarities to type classes. Rust's traits are a form of *bounded +polymorphism*: a trait is a way of limiting the set of possible types +that a type parameter could refer to. + +As motivation, let us consider copying in Rust. The `copy` operation +is not defined for all Rust types. One reason is user-defined +destructors: copying a type that has a destructor could result in the +destructor running multiple times. Therefore, types with user-defined +destructors cannot be copied, either implicitly or explicitly, and +neither can types that own other types containing destructors (see the +section on [structs](#structs) for the actual mechanism for defining +destructors). This complicates handling of generic functions. If you have a type parameter `T`, can you copy values of that type? In Rust, you can't, @@ -1890,8 +1899,8 @@ fn head_bad(v: &[T]) -> T { } ~~~~ -We can tell the compiler though that the `head` function is only for -copyable types with the `Copy` trait. +However, we can tell the compiler that the `head` function is only for +copyable types: that is, those that have the `Copy` trait. ~~~~ // This does @@ -1903,14 +1912,17 @@ fn head(v: &[T]) -> T { This says that we can call `head` on any type `T` as long as that type implements the `Copy` trait. When instantiating a generic function, you can only instantiate it with types that implement the correct -trait, so you could not apply `head` to a type with a destructor. +trait, so you could not apply `head` to a type with a +destructor. (`Copy` is a special trait that is built in to the +compiler, making it possible for the compiler to enforce this +restriction.) While most traits can be defined and implemented by user code, three traits are automatically derived and implemented for all applicable types by the compiler, and may not be overridden: -* `Copy` - Types that can be copied, either implicitly, or using the - `copy` expression. All types are copyable unless they are classes +* `Copy` - Types that can be copied: either implicitly, or explicitly with the + `copy` operator. All types are copyable unless they are classes with destructors or otherwise contain classes with destructors. * `Send` - Sendable (owned) types. All types are sendable unless they @@ -1957,7 +1969,7 @@ impl ~str: Printable { # (~"foo").print(); ~~~~ -Methods defined in an implementation of a trait may be called just as +Methods defined in an implementation of a trait may be called just like any other method, using dot notation, as in `1.print()`. Traits may themselves contain type parameters. A trait for generalized sequence types might look like the following: @@ -1979,14 +1991,14 @@ impl ~[T]: Seq { The implementation has to explicitly declare the type parameter that it binds, `T`, before using it to specify its trait type. Rust requires this declaration because the `impl` could also, for example, -specify an implementation of `Seq`. The trait type -- appearing -after the colon in the `impl` -- *refers* to a type, rather than +specify an implementation of `Seq`. The trait type (appearing +after the colon in the `impl`) *refers* to a type, rather than defining one. The type parameters bound by a trait are in scope in each of the method declarations. So, re-declaring the type parameter -`T` as an explicit type parameter for `len` -- in either the trait or -the impl -- would be a compile-time error. +`T` as an explicit type parameter for `len`, in either the trait or +the impl, would be a compile-time error. Within a trait definition, `self` is a special type that you can think of as a type parameter. An implementation of the trait for any given @@ -2006,16 +2018,17 @@ impl int: Eq { } ~~~~ -Notice that in the trait definition, `equals` takes a `self` type -argument, whereas, in the impl, `equals` takes an `int` type argument, -and uses `self` as the name of the receiver (analogous to the `this` pointer -in C++). +Notice that in the trait definition, `equals` takes a parameter of +type `self`. In contrast, in the `impl`, `equals` takes a parameter of +type `int`, and uses `self` as the name of the receiver (analogous to +the `this` pointer in C++). ## Bounded type parameters and static method dispatch -Traits give us a language for talking about the abstract capabilities -of types, and we can use this to place _bounds_ on type parameters, -so that we can then operate on generic types. +Traits give us a language for defining predicates on types, or +abstract properties that types can have. We can use this language to +define _bounds_ on type parameters, so that we can then operate on +generic types. ~~~~ # trait Printable { fn print(); } @@ -2026,14 +2039,14 @@ fn print_all(printable_things: ~[T]) { } ~~~~ -By declaring `T` as conforming to the `Printable` trait (as we earlier -did with `Copy`), it becomes possible to call methods from that trait -on values of that type inside the function. It will also cause a +Declaring `T` as conforming to the `Printable` trait (as we earlier +did with `Copy`) makes it possible to call methods from that trait +on values of type `T` inside the function. It will also cause a compile-time error when anyone tries to call `print_all` on an array whose element type does not have a `Printable` implementation. Type parameters can have multiple bounds by separating them with spaces, -as in this version of `print_all` that makes copies of elements. +as in this version of `print_all` that copies elements. ~~~ # trait Printable { fn print(); } @@ -2083,10 +2096,10 @@ fn draw_all(shapes: &[@Drawable]) { } ~~~~ -In this example there is no type parameter. Instead, the `@Drawable` -type is used to refer to any managed box value that implements the -`Drawable` trait. To construct such a value, you use the `as` operator -to cast a value to a trait type: +In this example, there is no type parameter. Instead, the `@Drawable` +type denotes any managed box value that implements the `Drawable` +trait. To construct such a value, you use the `as` operator to cast a +value to a trait type: ~~~~ # type Circle = int; type Rectangle = bool; @@ -2104,10 +2117,12 @@ let r: @Rectangle = @new_rectangle(); draw_all(&[c as @Drawable, r as @Drawable]); ~~~~ -Note that, like strings and vectors, trait types have dynamic size -and may only be used via one of the pointer types. In turn, the -`impl` is defined for `@Circle` and `@Rectangle` instead of for -just `Circle` and `Rectangle`. Other pointer types work as well. +We omit the code for `new_circle` and `new_rectangle`; imagine that +these just return `Circle`s and `Rectangle`s with a default size. Note +that, like strings and vectors, trait types have dynamic size and may +only be referred to via one of the pointer types. That's why the `impl` is +defined for `@Circle` and `@Rectangle` instead of for just `Circle` +and `Rectangle`. Other pointer types work as well. ~~~{.xfail-test} # type Circle = int; type Rectangle = int; @@ -2123,13 +2138,13 @@ let owny: ~Drawable = ~new_circle() as ~Drawable; let stacky: &Drawable = &new_circle() as &Drawable; ~~~ -> ***Note:*** Other pointer types actually _do not_ work here. This is +> ***Note:*** Other pointer types actually _do not_ work here yet. This is > an evolving corner of the language. Method calls to trait types are _dynamically dispatched_. Since the compiler doesn't know specifically which functions to call at compile -time it uses a lookup table (vtable) to decide at runtime which -method to call. +time it uses a lookup table (also known as a vtable or dictionary) to +select the method to call at runtime. This usage of traits is similar to Java interfaces. @@ -2170,17 +2185,18 @@ fn chicken_farmer() { ~~~ These farm animal functions have a new keyword, `pub`, attached to -them. This is a visibility modifier that allows item to be accessed -outside of the module in which they are declared, using `::`, as in -`farm::chicken`. Items, like `fn`, `struct`, etc. are private by -default. +them. The `pub` keyword modifies an item's visibility, making it +visible outside its containing module. An expression with `::`, like +`farm::chicken`, can name an item outside of its containing +module. Items, such as those declared with `fn`, `struct`, `enum`, +`type`, or `const`, are module-private by default. Visibility restrictions in Rust exist only at module boundaries. This -is quite different from most object-oriented languages that also enforce -restrictions on objects themselves. That's not to say that Rust doesn't -support encapsulation - both struct fields and methods can be private - -but it is at the module level, not the class level. Note that fields -and methods are _public_ by default. +is quite different from most object-oriented languages that also +enforce restrictions on objects themselves. That's not to say that +Rust doesn't support encapsulation: both struct fields and methods can +be private. But this encapsulation is at the module level, not the +struct level. Note that fields and methods are _public_ by default. ~~~ mod farm { @@ -2220,7 +2236,7 @@ fn main() { ## Crates -The unit of independent compilation in Rust is the crate - rustc +The unit of independent compilation in Rust is the crate: rustc compiles a single crate at a time, from which it produces either a library or executable. @@ -2294,22 +2310,24 @@ fn main() { bar::baz(); } ## Using other crates -Having compiled a crate into a library you can use it in another crate -with an `extern mod` directive. `extern mod` can appear at the top of -a crate file or at the top of modules. It will cause the compiler to -look in the library search path (which you can extend with `-L` -switch) for a compiled Rust library with the right name, then add a -module with that crate's name into the local scope. +The `extern mod` directive lets you use a crate (once it's been +compiled into a library) from inside another crate. `extern mod` can +appear at the top of a crate file or at the top of modules. It will +cause the compiler to look in the library search path (which you can +extend with the `-L` switch) for a compiled Rust library with the +right name, then add a module with that crate's name into the local +scope. For example, `extern mod std` links the [standard library]. [standard library]: std/index.html -When a comma-separated list of name/value pairs is given after `extern -mod`, these are matched against the attributes provided in the `link` -attribute of the crate file, and a crate is only used when the two -match. A `name` value can be given to override the name used to search -for the crate. +When a comma-separated list of name/value pairs appears after `extern +mod`, the compiler front-end matches these pairs against the +attributes provided in the `link` attribute of the crate file. The +front-end will only select this crate for use if the actual pairs +match the declared attributes. You can provide a `name` value to +override the name used to search for the crate. Our example crate declared this set of `link` attributes: @@ -2317,7 +2335,7 @@ Our example crate declared this set of `link` attributes: #[link(name = "farm", vers = "2.5", author = "mjh")]; ~~~~ -Which can then be linked with any (or all) of the following: +Which you can then link with any (or all) of the following: ~~~~ {.xfail-test} extern mod farm; @@ -2325,7 +2343,7 @@ extern mod my_farm (name = "farm", vers = "2.5"); extern mod my_auxiliary_farm (name = "farm", author = "mjh"); ~~~~ -If any of the requested metadata does not match then the crate +If any of the requested metadata do not match, then the crate will not be compiled successfully. ## A minimal example @@ -2361,7 +2379,7 @@ a hash representing the crate metadata. ## The core library -The Rust [core] library acts as the language runtime and contains +The Rust [core] library is the language runtime and contains required memory management and task scheduling code as well as a number of modules necessary for effective usage of the primitive types. Methods on [vectors] and [strings], implementations of most -- cgit 1.4.1-3-g733a5 From 41bce91cb871ba90caf7d3e56243141dd3390bca Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Thu, 11 Oct 2012 14:10:05 -0700 Subject: Fix tutorial link to tasks Closes #3715 --- doc/tutorial.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index ae88cda8d8e..04fd2aae3f7 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1630,7 +1630,9 @@ hold on to things that can safely be sent between processes. They copy the values they close over, much like managed closures, but they also own them: that is, no other code can access them. Owned closures are used in concurrent code, particularly -for spawning [tasks](#tasks). +for spawning [tasks][tasks]. + +[tasks]: tutorial-tasks.html ## Closure compatibility -- cgit 1.4.1-3-g733a5 From c33bff955707d496d675126433627297487daa25 Mon Sep 17 00:00:00 2001 From: Daniel Patterson Date: Thu, 11 Oct 2012 23:13:04 -0400 Subject: tutorial: add note about mutability of vectors --- doc/tutorial.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index 04fd2aae3f7..12850a92a03 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -216,7 +216,7 @@ while count < 10 { Although Rust can almost always infer the types of local variables, you can specify a variable's type by following it with a colon, then the type -name. +name. ~~~~ let monster_size: float = 57.8; @@ -381,6 +381,10 @@ of: `[mut T]` Mutable vector with unknown size ------------------------- ----------------------------------------------- +> ***Note***: In the future, mutability for vectors may be defined by +> the slot that contains the vector, not the type of the vector itself, +> deprecating [mut T] syntax. + In function types, the return type is specified with an arrow, as in the type `fn() -> bool` or the function declaration `fn foo() -> bool { }`. For functions that do not return a meaningful value, you can @@ -1951,7 +1955,7 @@ trait Printable { ~~~~ Traits may be implemented for specific types with [impls]. An impl -that implements a trait includes the name of the trait at the start of +that implements a trait includes the name of the trait at the start of the definition, as in the following impls of `Printable` for `int` and `~str`. -- cgit 1.4.1-3-g733a5 From ea5e3d21ff5ef8b4d30b588d0cd65859ffa3bab1 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Tue, 18 Sep 2012 22:33:49 -0700 Subject: Make moves explicit in doc examples Had to remove the buffalo example. It was awkward to update for explicit moves. --- doc/tutorial-tasks.md | 18 +++++++++--------- doc/tutorial.md | 2 +- src/test/run-pass/issue-3668.rs | 13 +++++++++++++ src/test/run-pass/issue-3688-2.rs | 5 +++++ 4 files changed, 28 insertions(+), 10 deletions(-) create mode 100644 src/test/run-pass/issue-3668.rs create mode 100644 src/test/run-pass/issue-3688-2.rs (limited to 'doc/tutorial.md') diff --git a/doc/tutorial-tasks.md b/doc/tutorial-tasks.md index 8a0cda3e820..2d203400dda 100644 --- a/doc/tutorial-tasks.md +++ b/doc/tutorial-tasks.md @@ -161,7 +161,7 @@ use pipes::{stream, Port, Chan}; let (chan, port): (Chan, Port) = stream(); -do spawn { +do spawn |move chan| { let result = some_expensive_computation(); chan.send(result); } @@ -192,7 +192,7 @@ spawns the child task. # use pipes::{stream, Port, Chan}; # fn some_expensive_computation() -> int { 42 } # let (chan, port) = stream(); -do spawn { +do spawn |move chan| { let result = some_expensive_computation(); chan.send(result); } @@ -229,7 +229,7 @@ following program is ill-typed: # fn some_expensive_computation() -> int { 42 } let (chan, port) = stream(); -do spawn { +do spawn |move chan| { chan.send(some_expensive_computation()); } @@ -253,7 +253,7 @@ let chan = SharedChan(move chan); for uint::range(0, 3) |init_val| { // Create a new channel handle to distribute to the child task let child_chan = chan.clone(); - do spawn { + do spawn |move child_chan| { child_chan.send(some_expensive_computation(init_val)); } } @@ -283,10 +283,10 @@ might look like the example below. // Create a vector of ports, one for each child task let ports = do vec::from_fn(3) |init_val| { let (chan, port) = stream(); - do spawn { + do spawn |move chan| { chan.send(some_expensive_computation(init_val)); } - port + move port }; // Wait on each port, accumulating the results @@ -398,13 +398,13 @@ before returning. Hence: # fn sleep_forever() { loop { task::yield() } } # do task::try { let (sender, receiver): (Chan, Port) = stream(); -do spawn { // Bidirectionally linked +do spawn |move receiver| { // Bidirectionally linked // Wait for the supervised child task to exist. let message = receiver.recv(); // Kill both it and the parent task. assert message != 42; } -do try { // Unidirectionally linked +do try |move sender| { // Unidirectionally linked sender.send(42); sleep_forever(); // Will get woken up by force } @@ -505,7 +505,7 @@ Here is the code for the parent task: let (from_child, to_child) = DuplexStream(); -do spawn || { +do spawn |move to_child| { stringifier(&to_child); }; diff --git a/doc/tutorial.md b/doc/tutorial.md index 12850a92a03..8746cf026f9 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1827,7 +1827,7 @@ fn map(vector: &[T], function: fn(v: &T) -> U) -> ~[U] { for vec::each(vector) |element| { accumulator.push(function(element)); } - return accumulator; + return (move accumulator); } ~~~~ diff --git a/src/test/run-pass/issue-3668.rs b/src/test/run-pass/issue-3668.rs new file mode 100644 index 00000000000..5f677767240 --- /dev/null +++ b/src/test/run-pass/issue-3668.rs @@ -0,0 +1,13 @@ +struct P { child: Option<@mut P> } +trait PTrait { + fn getChildOption() -> Option<@P>; +} + +impl P: PTrait { + fn getChildOption() -> Option<@P> { + const childVal: @P = self.child.get(); + fail; + } +} + +fn main() {} diff --git a/src/test/run-pass/issue-3688-2.rs b/src/test/run-pass/issue-3688-2.rs new file mode 100644 index 00000000000..018bd1d2a8d --- /dev/null +++ b/src/test/run-pass/issue-3688-2.rs @@ -0,0 +1,5 @@ + fn f(x:int) { + const child: int = x + 1; + } + +fn main() {} -- cgit 1.4.1-3-g733a5 From a92c3db0b34905e7a828bb72931b791818a02b6b Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Tue, 16 Oct 2012 20:19:34 -0700 Subject: add missing pub from multifile example in sec 12.3 --- doc/tutorial.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index 8746cf026f9..645e150b40a 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -2360,7 +2360,7 @@ these two files: ~~~~ // world.rs #[link(name = "world", vers = "1.0")]; -fn explore() -> ~str { ~"world" } +pub fn explore() -> ~str { ~"world" } ~~~~ ~~~~ {.xfail-test} -- cgit 1.4.1-3-g733a5 From e94e82cb8ef0491667bc8041d370199aed838f2d Mon Sep 17 00:00:00 2001 From: Ben Striegel Date: Fri, 12 Oct 2012 19:41:16 -0400 Subject: Extraneous sigil patrol: ~"string literals" --- doc/tutorial.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index 645e150b40a..b411e1232b7 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1502,7 +1502,7 @@ and [`core::str`]. Here are some examples. # fn unwrap_crayon(c: Crayon) -> int { 0 } # fn eat_crayon_wax(i: int) { } # fn store_crayon_in_nasal_cavity(i: uint, c: Crayon) { } -# fn crayon_to_str(c: Crayon) -> ~str { ~"" } +# fn crayon_to_str(c: Crayon) -> &str { "" } let crayons = &[Almond, AntiqueBrass, Apricot]; @@ -1649,11 +1649,11 @@ callers may pass any kind of closure. ~~~~ fn call_twice(f: fn()) { f(); f(); } -call_twice(|| { ~"I am an inferred stack closure"; } ); -call_twice(fn&() { ~"I am also a stack closure"; } ); -call_twice(fn@() { ~"I am a managed closure"; }); -call_twice(fn~() { ~"I am an owned closure"; }); -fn bare_function() { ~"I am a plain function"; } +call_twice(|| { "I am an inferred stack closure"; } ); +call_twice(fn&() { "I am also a stack closure"; } ); +call_twice(fn@() { "I am a managed closure"; }); +call_twice(fn~() { "I am an owned closure"; }); +fn bare_function() { "I am a plain function"; } call_twice(bare_function); ~~~~ @@ -1767,7 +1767,7 @@ And using this function to iterate over a vector: # use println = io::println; each(&[2, 4, 8, 5, 16], |n| { if *n % 2 != 0 { - println(~"found odd number!"); + println("found odd number!"); false } else { true } }); @@ -1784,7 +1784,7 @@ to the next iteration, write `loop`. # use println = io::println; for each(&[2, 4, 8, 5, 16]) |n| { if *n % 2 != 0 { - println(~"found odd number!"); + println("found odd number!"); break; } } @@ -1967,12 +1967,12 @@ impl int: Printable { fn print() { io::println(fmt!("%d", self)) } } -impl ~str: Printable { +impl &str: Printable { fn print() { io::println(self) } } # 1.print(); -# (~"foo").print(); +# ("foo").print(); ~~~~ Methods defined in an implementation of a trait may be called just like @@ -2162,8 +2162,8 @@ additional modules. ~~~~ mod farm { - pub fn chicken() -> ~str { ~"cluck cluck" } - pub fn cow() -> ~str { ~"mooo" } + pub fn chicken() -> &str { "cluck cluck" } + pub fn cow() -> &str { "mooo" } } fn main() { @@ -2360,13 +2360,13 @@ these two files: ~~~~ // world.rs #[link(name = "world", vers = "1.0")]; -pub fn explore() -> ~str { ~"world" } +pub fn explore() -> &str { "world" } ~~~~ ~~~~ {.xfail-test} // main.rs extern mod world; -fn main() { io::println(~"hello " + world::explore()); } +fn main() { io::println("hello " + world::explore()); } ~~~~ Now compile and run like this (adjust to your platform if necessary): -- cgit 1.4.1-3-g733a5 From 5e1d0bab8075df5ce06543537296d7294440bd45 Mon Sep 17 00:00:00 2001 From: Ben Striegel Date: Fri, 12 Oct 2012 20:48:45 -0400 Subject: Sigil patrol: change fn@ fn& fn~ to @fn &fn ~fn This also involves removing references to the old long-form closure syntax, which pcwalton alleges is deprecated and which was never updated for the new forms, e.g. `@fn() {}` is illegal. --- doc/tutorial.md | 36 +++++++++++------------------------- 1 file changed, 11 insertions(+), 25 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index b411e1232b7..67c9bcd8281 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1569,7 +1569,7 @@ let bloop = |well, oh: mygoodness| -> what_the { fail oh(well) }; ~~~~ There are several forms of closure, each with its own role. The most -common, called a _stack closure_, has type `fn&` and can directly +common, called a _stack closure_, has type `&fn` and can directly access local variables in the enclosing scope. ~~~~ @@ -1591,7 +1591,7 @@ pervasively in Rust code. When you need to store a closure in a data structure, a stack closure will not do, since the compiler will refuse to let you store it. For this purpose, Rust provides a type of closure that has an arbitrary -lifetime, written `fn@` (boxed closure, analogous to the `@` pointer +lifetime, written `@fn` (boxed closure, analogous to the `@` pointer type described earlier). This type of closure *is* first-class. A managed closure does not directly access its environment, but merely @@ -1604,8 +1604,9 @@ returns it from a function, and then calls it: ~~~~ # extern mod std; -fn mk_appender(suffix: ~str) -> fn@(~str) -> ~str { - return fn@(s: ~str) -> ~str { s + suffix }; +fn mk_appender(suffix: ~str) -> @fn(~str) -> ~str { + // The compiler knows that we intend this closure to be of type @fn + return |s| s + suffix; } fn main() { @@ -1614,22 +1615,9 @@ fn main() { } ~~~~ -This example uses the long closure syntax, `fn@(s: ~str) ...`. Using -this syntax makes it explicit that we are declaring a boxed -closure. In practice, boxed closures are usually defined with the -short closure syntax introduced earlier, in which case the compiler -infers the type of closure. Thus our managed closure example could -also be written: - -~~~~ -fn mk_appender(suffix: ~str) -> fn@(~str) -> ~str { - return |s| s + suffix; -} -~~~~ - ## Owned closures -Owned closures, written `fn~` in analogy to the `~` pointer type, +Owned closures, written `~fn` in analogy to the `~` pointer type, hold on to things that can safely be sent between processes. They copy the values they close over, much like managed closures, but they also own them: that is, no other code can access @@ -1649,12 +1637,10 @@ callers may pass any kind of closure. ~~~~ fn call_twice(f: fn()) { f(); f(); } -call_twice(|| { "I am an inferred stack closure"; } ); -call_twice(fn&() { "I am also a stack closure"; } ); -call_twice(fn@() { "I am a managed closure"; }); -call_twice(fn~() { "I am an owned closure"; }); -fn bare_function() { "I am a plain function"; } -call_twice(bare_function); +let closure = || { "I'm a closure, and it doesn't matter what type I am"; }; +fn function() { "I'm a normal function"; } +call_twice(closure); +call_twice(function); ~~~~ > ***Note:*** Both the syntax and the semantics will be changing @@ -1715,7 +1701,7 @@ parentheses, where it looks more like a typical block of code. `do` is a convenient way to create tasks with the `task::spawn` -function. `spawn` has the signature `spawn(fn: fn~())`. In other +function. `spawn` has the signature `spawn(fn: ~fn())`. In other words, it is a function that takes an owned closure that takes no arguments. -- cgit 1.4.1-3-g733a5 From f7ce3dc55f1bcc8a741951a4b9f090bad61769ae Mon Sep 17 00:00:00 2001 From: Ben Striegel Date: Fri, 12 Oct 2012 21:47:46 -0400 Subject: Extraneous sigil patrol: turn &[] literals into [] --- doc/tutorial.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'doc/tutorial.md') diff --git a/doc/tutorial.md b/doc/tutorial.md index 67c9bcd8281..02927c4ddd1 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1504,7 +1504,7 @@ and [`core::str`]. Here are some examples. # fn store_crayon_in_nasal_cavity(i: uint, c: Crayon) { } # fn crayon_to_str(c: Crayon) -> &str { "" } -let crayons = &[Almond, AntiqueBrass, Apricot]; +let crayons = [Almond, AntiqueBrass, Apricot]; // Check the length of the vector assert crayons.len() == 3; @@ -1679,7 +1679,7 @@ structure. ~~~~ # fn each(v: &[int], op: fn(v: &int)) { } # fn do_some_work(i: &int) { } -each(&[1, 2, 3], |n| { +each([1, 2, 3], |n| { do_some_work(n); }); ~~~~ @@ -1690,7 +1690,7 @@ call that can be written more like a built-in control structure: ~~~~ # fn each(v: &[int], op: fn(v: &int)) { } # fn do_some_work(i: &int) { } -do each(&[1, 2, 3]) |n| { +do each([1, 2, 3]) |n| { do_some_work(n); } ~~~~ @@ -1751,7 +1751,7 @@ And using this function to iterate over a vector: ~~~~ # use each = vec::each; # use println = io::println; -each(&[2, 4, 8, 5, 16], |n| { +each([2, 4, 8, 5, 16], |n| { if *n % 2 != 0 { println("found odd number!"); false @@ -1768,7 +1768,7 @@ to the next iteration, write `loop`. ~~~~ # use each = vec::each; # use println = io::println; -for each(&[2, 4, 8, 5, 16]) |n| { +for each([2, 4, 8, 5, 16]) |n| { if *n % 2 != 0 { println("found odd number!"); break; @@ -2106,7 +2106,7 @@ impl @Rectangle: Drawable { fn draw() { ... } } let c: @Circle = @new_circle(); let r: @Rectangle = @new_rectangle(); -draw_all(&[c as @Drawable, r as @Drawable]); +draw_all([c as @Drawable, r as @Drawable]); ~~~~ We omit the code for `new_circle` and `new_rectangle`; imagine that -- cgit 1.4.1-3-g733a5