@@ -133,7 +133,8 @@ the documentation for your shell for more details.
133
133
134
134
Let's make a new source file next. I'm going to use the syntax `editor
135
135
filename` to represent editing a file in these examples, but you should use
136
- whatever method you want. We'll call our file ` main.rs ` :
136
+ whatever method you want (if you are new to * NIX try out emacs or vim investing
137
+ time in them really is useful). We'll call our file ` main.rs ` :
137
138
138
139
``` {bash}
139
140
$ editor main.rs
@@ -170,11 +171,11 @@ fn main() {
170
171
These lines define a ** function** in Rust. The ` main ` function is special:
171
172
it's the beginning of every Rust program. The first line says "I'm declaring a
172
173
function named ` main ` , which takes no arguments and returns nothing." If there
173
- were arguments, they would go inside the parentheses ( ` ( ` and ` ) ` ), and because
174
- we aren't returning anything from this function, we've dropped that notation
175
- entirely. We'll get to it later.
174
+ were arguments, they would go inside the parentheses after the function name.
175
+ Since we aren't returning anything from this function, we've dropped that notation
176
+ entirely. We'll get to it later.
176
177
177
- You'll also note that the function is wrapped in curly braces ( ` { ` and ` } ` ) .
178
+ You'll also note that the function is wrapped in curly braces.
178
179
Rust requires these around all function bodies. It is also considered good
179
180
style to put the opening curly brace on the same line as the function
180
181
declaration, with one space in between.
@@ -192,7 +193,8 @@ with the tab key. We provide some [sample configurations for various
192
193
editors] ( https://github.com/rust-lang/rust/tree/master/src/etc ) .
193
194
194
195
The second point is the ` println!() ` part. This is calling a Rust ** macro** ,
195
- which is how metaprogramming is done in Rust. If it were a function instead, it
196
+ which is how [ metaprogramming] ( http://en.wikipedia.org/wiki/Metaprogramming )
197
+ (programs that write programs) is done in Rust. If it were a function instead, it
196
198
would look like this: ` println() ` . For our purposes, we don't need to worry
197
199
about this difference. Just know that sometimes, you'll see a ` ! ` , and that
198
200
means that you're calling a macro instead of a normal function. Rust implements
@@ -248,7 +250,7 @@ This prints out our `Hello, world!` text to our terminal.
248
250
If you come from a dynamically typed language like Ruby, Python, or JavaScript,
249
251
you may not be used to these two steps being separate. Rust is an
250
252
** ahead-of-time compiled language** , which means that you can compile a
251
- program, give it to someone else, and they don't need to have Rust installed .
253
+ program, give it to someone else, and they don't need to have a ` Rust ` compiler .
252
254
If you give someone a ` .rb ` or ` .py ` or ` .js ` file, they need to have
253
255
Ruby/Python/JavaScript installed, but you just need one command to both compile
254
256
and run your program. Everything is a tradeoff in language design, and Rust has
@@ -438,10 +440,10 @@ something you may not have cared to mutate. If bindings were mutable by
438
440
default, the compiler would not be able to tell you this. If you _ did_ intend
439
441
mutation, then the solution is quite easy: add ` mut ` .
440
442
441
- There are other good reasons to avoid mutable state when possible, but they're
442
- out of the scope of this guide. In general, you can often avoid explicit
443
- mutation, and so it is preferable in Rust. That said, sometimes, mutation is
444
- what you need, so it's not verboten.
443
+ There are other good reasons to avoid mutable state when possible (mostly
444
+ parallelism, concurrency and code generation) , but we won't go into the details
445
+ in this guide. In general, you can often avoid explicit mutation, and so it is
446
+ preferable in Rust. That said, sometimes, mutation is what you need, so it's not verboten.
445
447
446
448
Let's get back to bindings. Rust variable bindings have one more aspect that
447
449
differs from other languages: bindings are required to be initialized with a
@@ -660,7 +662,7 @@ Note the semicolons after the 10 and 15. Rust will give us the following error:
660
662
error: mismatched types: expected `int` but found `()` (expected int but found ())
661
663
```
662
664
663
- We expected an integer, but we got ` () ` . ` () ` is pronounced 'unit', and is a
665
+ We expected an integer, but we got ` () ` . ` () ` is pronounced 'unit,' and is a
664
666
special type in Rust's type system. In Rust, ` () ` is _ not_ a valid value for a
665
667
variable of type ` int ` . It's only a valid value for variables of the type ` () ` ,
666
668
which aren't very useful. Remember how we said statements don't return a value?
@@ -681,8 +683,8 @@ fn main() {
681
683
```
682
684
683
685
This is the simplest possible function declaration. As we mentioned before,
684
- ` fn ` says 'this is a function,' followed by the name, some parenthesis because
685
- this function takes no arguments, and then some curly braces to indicate the
686
+ ` fn ` says 'this is a function,' followed by the name, nothing in the parentheses
687
+ because this function takes no arguments, and then some curly braces to indicate the
686
688
body. Here's a function named ` foo ` :
687
689
688
690
``` {rust}
@@ -710,7 +712,7 @@ fn print_number(x: int) {
710
712
}
711
713
```
712
714
713
- As you can see, function arguments work very similar to ` let ` declarations:
715
+ As you can see, function arguments declarations work very similar to ` let ` declarations:
714
716
you add a type to the argument name, after a colon.
715
717
716
718
Here's a complete program that adds two numbers together and prints them:
@@ -750,17 +752,27 @@ types explicitly is a best-practice. We agree that forcing functions to declare
750
752
types while allowing for inference inside of function bodies is a wonderful
751
753
sweet spot between full inference and no inference.
752
754
753
- What about returning a value? Here's a function that adds one to an integer:
755
+ What about returning a value?
756
+ Rust functions return exactly one value, the type of which is declared after an arrow
757
+ (` -> ` ) in the function declaration. Here is the declaration of a function that
758
+ returns an ` int ` :
759
+
760
+ ``` {rust, ignore}
761
+ fn returns_int() -> int {
762
+ //...
763
+ }
764
+ ```
765
+
766
+ Rust function usually return their last expression as return value.
767
+ Here's a function that adds one to an integer:
754
768
755
769
``` {rust}
756
770
fn add_one(x: int) -> int {
757
771
x + 1
758
772
}
759
773
```
760
774
761
- Rust functions return exactly one value, and you declare the type after an
762
- 'arrow', which is a dash (` - ` ) followed by a greater-than sign (` > ` ).
763
-
775
+ As you can see the last line evaluates to an ` int ` , which is the return type of the function.
764
776
You'll note the lack of a semicolon here. If we added it in:
765
777
766
778
``` {ignore}
@@ -822,8 +834,8 @@ that we haven't learned about yet, so let's just leave it at that for now.
822
834
# Comments
823
835
824
836
Now that we have some functions, it's a good idea to learn about comments.
825
- Comments are notes that you leave to other programmers to help explain things
826
- about your code. The compiler mostly ignores them.
837
+ Comments are notes that you leave to other programmers (and your future self)
838
+ to help explain things about your code. The compiler mostly ignores them.
827
839
828
840
Rust has two kinds of comments that you should care about: ** line comment** s
829
841
and ** doc comment** s.
@@ -882,7 +894,7 @@ Tuples are an ordered list of a fixed size. Like this:
882
894
let x = (1i , " hello" );
883
895
```
884
896
885
- The parenthesis and commas form this two-length tuple. Here's the same code, but
897
+ The parentheses and commas form this two-length tuple. Here's the same code, but
886
898
with the type annotated:
887
899
888
900
``` rust
@@ -1066,7 +1078,7 @@ destructuring `let`.
1066
1078
1067
1079
## Enums
1068
1080
1069
- Finally, Rust has a " sum type", an ** enum** . Enums are an incredibly useful
1081
+ Finally, Rust has a ' sum type,' an ** enum** . Enums are an incredibly useful
1070
1082
feature of Rust, and are used throughout the standard library. This is an enum
1071
1083
that is provided by the Rust standard library:
1072
1084
@@ -1283,6 +1295,8 @@ It can also allow us to treat errors or unexpected computations, for example, a
1283
1295
function that is not guaranteed to be able to compute a result (an ` int ` here),
1284
1296
could return an ` OptionalInt ` , and we would handle that value with a ` match ` .
1285
1297
As you can see, ` enum ` and ` match ` used together are quite useful!
1298
+ They are also the only way to get the values contained in an
1299
+ ` enum ` .
1286
1300
1287
1301
` match ` is also an expression, which means we can use it on the right
1288
1302
hand side of a ` let ` binding or directly where an expression is
@@ -1542,8 +1556,8 @@ always initialized.
1542
1556
let a = [0i, ..20]; // Shorthand for array of 20 elements all initialized to 0
1543
1557
```
1544
1558
1545
- Arrays have type ` [T,..N] ` . We'll talk about this ` T ` notation later, when we
1546
- cover generics.
1559
+ An array of ` N ` elements of type ` T ` has type ` [T,..N] ` . We'll talk about this ` T `
1560
+ notation later, when we cover generics.
1547
1561
1548
1562
You can get the number of elements in an array ` a ` with ` a.len() ` , and use
1549
1563
` a.iter() ` to iterate over them with a for loop. This code will print each
@@ -1591,6 +1605,7 @@ arrays. In addition, (mutable) vectors can grow automatically:
1591
1605
1592
1606
``` {rust}
1593
1607
let mut nums = vec![1i, 2, 3];
1608
+ println!("The length of nums is {}", nums.len()); // Prints 3
1594
1609
nums.push(4);
1595
1610
println!("The length of nums is now {}", nums.len()); // Prints 4
1596
1611
```
@@ -1645,7 +1660,7 @@ std::io::stdin();
1645
1660
```
1646
1661
1647
1662
This calls a function, ` stdin() ` , that lives inside the ` std::io ` module. As
1648
- you can imagine, everything in ` std ` is provided by Rust, the 'standard
1663
+ you can imagine, everything in ` std ` is provided by Rust's 'standard
1649
1664
library.' We'll talk more about the module system later.
1650
1665
1651
1666
Since writing the fully qualified name all the time is annoying, we can use
@@ -1739,7 +1754,7 @@ doesn't work, so we're okay with that. In most cases, we would want to handle
1739
1754
the error case explicitly. ` expect() ` allows us to give an error message if
1740
1755
this crash happens.
1741
1756
1742
- We will cover the exact details of how all of this works later in the Guide.
1757
+ We will cover the exact details of how all of this works in another Guide.
1743
1758
For now, this gives you enough of a basic understanding to work with.
1744
1759
1745
1760
Back to the code we were working on! Here's a refresher:
@@ -1931,7 +1946,7 @@ explained. We then added in a `let` expression to create a variable binding
1931
1946
named ` secret_number ` , and we printed out its result.
1932
1947
1933
1948
Also, you may wonder why we are using ` % ` on the result of ` rand::random() ` .
1934
- This operator is called 'modulo', and it returns the remainder of a division.
1949
+ This operator is called 'modulo,' and it returns the remainder of a division.
1935
1950
By taking the modulo of the result of ` rand::random() ` , we're limiting the
1936
1951
values to be between 0 and 99. Then, we add one to the result, making it from 1
1937
1952
to 100. Using modulo can give you a very, very small bias in the result, but
@@ -2778,7 +2793,7 @@ mod hello {
2778
2793
}
2779
2794
```
2780
2795
2781
- Usage of the ` pub ` keyword is sometimes called 'exporting', because
2796
+ Usage of the ` pub ` keyword is sometimes called 'exporting,' because
2782
2797
we're making the function available for other modules. This will work:
2783
2798
2784
2799
``` {notrust,ignore}
@@ -2791,6 +2806,8 @@ Hello, world!
2791
2806
Nice! There are more things we can do with modules, including moving them into
2792
2807
their own files. This is enough detail for now.
2793
2808
2809
+ More can be found in the [ Crates and Modules Guide] ( http://doc.rust-lang.org/guide-crates.html ) .
2810
+
2794
2811
# Testing
2795
2812
2796
2813
Traditionally, testing has not been a strong suit of most systems programming
@@ -3524,7 +3541,7 @@ difficult.
3524
3541
Rust chooses a different path, and that path is called ** ownership** . Any
3525
3542
binding that creates a resource is the ** owner** of that resource.
3526
3543
3527
- Being an owner affords you some privileges:
3544
+ Being an owner grants you some privileges:
3528
3545
3529
3546
1 . You control when that resource is deallocated.
3530
3547
2 . You may lend that resource, immutably, to as many borrowers as you'd like.
@@ -4111,14 +4128,20 @@ binding name and two parentheses, just like we would for a named function.
4111
4128
Let's compare syntax. The two are pretty close:
4112
4129
4113
4130
``` {rust}
4114
- let add_one = |x: int| -> int { 1i + x };
4131
+ let add_one = |x| { 1i + x };
4115
4132
fn add_one (x: int) -> int { 1i + x }
4116
4133
```
4117
4134
4118
4135
As you may have noticed, closures infer their argument and return types, so you
4119
4136
don't need to declare one. This is different from named functions, which
4120
4137
default to returning unit (` () ` ).
4121
4138
4139
+ Nevertheless, we can still declare argument and return types as follows:
4140
+
4141
+ ``` {rust}
4142
+ let add_one = |x: int| -> int { 1i + x };
4143
+ ```
4144
+
4122
4145
There's one big difference between a closure and named functions, and it's in
4123
4146
the name: a closure "closes over its environment." What does that mean? It means
4124
4147
this:
@@ -4190,7 +4213,7 @@ fn twice(x: int, f: |int| -> int) -> int {
4190
4213
}
4191
4214
4192
4215
fn main() {
4193
- let square = |x: int| { x * x };
4216
+ let square = |x: int| -> int { x * x };
4194
4217
4195
4218
twice(5i, square); // evaluates to 50
4196
4219
}
@@ -4199,7 +4222,7 @@ fn main() {
4199
4222
Let's break the example down, starting with ` main ` :
4200
4223
4201
4224
``` {rust}
4202
- let square = |x: int| { x * x };
4225
+ let square = |x: int| -> int { x * x };
4203
4226
```
4204
4227
4205
4228
We've seen this before. We make a closure that takes an integer, and returns
@@ -4266,7 +4289,7 @@ fn twice(x: int, f: |int| -> int) -> int {
4266
4289
}
4267
4290
4268
4291
fn main() {
4269
- twice(5i, |x: int| { x * x }); // evaluates to 50
4292
+ twice(5i, |x: int| -> int { x * x }); // evaluates to 50
4270
4293
}
4271
4294
```
4272
4295
@@ -4450,7 +4473,7 @@ Another important consumer is `fold`. Here's what it looks like:
4450
4473
4451
4474
``` {rust}
4452
4475
let sum = range(1i, 4i)
4453
- .fold(0i, |sum , x| sum + x);
4476
+ .fold(0i, |acc , x| acc + x);
4454
4477
```
4455
4478
4456
4479
` fold() ` is a consumer that looks like this:
@@ -4518,8 +4541,8 @@ Now, `collect()` will require that `range()` give it some numbers, and so
4518
4541
it will do the work of generating the sequence.
4519
4542
4520
4543
` range ` is one of two basic iterators that you'll see. The other is ` iter() ` ,
4521
- which you've used before. ` iter() ` can turn a vector into a simple iterator
4522
- that gives you each element in turn:
4544
+ which you've used before. ` iter() ` can turn an iterable structure, such as a
4545
+ vector or a list, into a simple iterator that gives you each element in turn:
4523
4546
4524
4547
``` {rust}
4525
4548
let nums = [1i, 2i, 3i];
@@ -4722,9 +4745,9 @@ enum Result<H, N> {
4722
4745
if we wanted to. Convention says that the first generic parameter should be
4723
4746
` T ` , for 'type,' and that we use ` E ` for 'error.' Rust doesn't care, however.
4724
4747
4725
- The ` Result<T, E> ` type is intended to
4726
- be used to return the result of a computation, and to have the ability to
4727
- return an error if it didn't work out . Here's an example:
4748
+ The ` Result<T, E> ` type is intended to be used to return the result of a computation,
4749
+ and to have the ability to return an error if it didn't work out, just as we saw
4750
+ in the enum chapter . Here's an example:
4728
4751
4729
4752
``` {rust}
4730
4753
let x: Result<f64, String> = Ok(2.3f64);
@@ -5247,7 +5270,7 @@ immediately.
5247
5270
5248
5271
## Success and failure
5249
5272
5250
- Tasks don't always succeed, they can also panic. A task that wishes to panic
5273
+ Tasks don't always succeed, they can also panic. A task that wishes to panic
5251
5274
can call the ` panic! ` macro, passing a message:
5252
5275
5253
5276
``` {rust}
@@ -5284,7 +5307,7 @@ allow you to provide abstractions over syntax. Do you wish Rust had the ability
5284
5307
to do something that it can't currently do? You may be able to write a macro
5285
5308
to extend Rust's capabilities.
5286
5309
5287
- You've already used one macro extensively: ` println! ` . When we invoke
5310
+ You've already used two macros extensively: ` println! ` and ` vec !` . When we invoke
5288
5311
a Rust macro, we need to use the exclamation mark (` ! ` ). There are two reasons
5289
5312
why this is so: the first is that it makes it clear when you're using a
5290
5313
macro. The second is that macros allow for flexible syntax, and so Rust must
@@ -5364,8 +5387,7 @@ this by hand to get a type-checked `println`.
5364
5387
5365
5388
For more on macros, please consult [ the Macros Guide] ( guide-macros.html ) .
5366
5389
Macros are a very advanced and still slightly experimental feature, but they don't
5367
- require a deep understanding to be called, since they look just like functions. The
5368
- Guide can help you if you want to write your own.
5390
+ require a deep understanding to be called, since they look just like functions.
5369
5391
5370
5392
# Unsafe
5371
5393
0 commit comments