Skip to content

Commit

Permalink
Merge pull request #1 from rust-lang/master
Browse files Browse the repository at this point in the history
Update fork
  • Loading branch information
andymac-2 authored Sep 24, 2019
2 parents 67cfbf3 + a0164b7 commit e60b98d
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 39 deletions.
6 changes: 3 additions & 3 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
- [As output parameters](fn/closures/output_parameters.md)
- [Examples in `std`](fn/closures/closure_examples.md)
- [Iterator::any](fn/closures/closure_examples/iter_any.md)
- [Iterator::find](fn/closures/closure_examples/iter_find.md)
- [Searching through iterators](fn/closures/closure_examples/iter_find.md)
- [Higher Order Functions](fn/hof.md)
- [Diverging functions](fn/diverging.md)

Expand Down Expand Up @@ -139,8 +139,8 @@
- [Iterators](trait/iter.md)
- [`impl Trait`](trait/impl_trait.md)
- [Clone](trait/clone.md)
- [Supertraits](traits/supertraits.md)
- [Disambiguating overlapping traits](traits/disambiguating.md)
- [Supertraits](trait/supertraits.md)
- [Disambiguating overlapping traits](trait/disambiguating.md)

- [macro_rules!](macros.md)
- [Syntax](macros/syntax.md)
Expand Down
2 changes: 1 addition & 1 deletion src/conversion/string.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ trait is implemented for that type. This is implemented for numerous types
within the standard library. To obtain this functionality on a user defined type
simply implement the [`FromStr`] trait for that type.

```rust
```rust,editable
fn main() {
let parsed: i32 = "5".parse().unwrap();
let turbo_parsed = "10".parse::<i32>().unwrap();
Expand Down
9 changes: 5 additions & 4 deletions src/custom_types/enum.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ fn main() {

## Type aliases

If you use a type alias, you can refer to each enum variant via its alias.
If you use a type alias, you can refer to each enum variant via its alias.
This might be useful if the enum's name is too long or too generic, and you
want to rename it.

Expand Down Expand Up @@ -93,16 +93,17 @@ impl VeryVerboseEnumOfThingsToDoWithNumbers {
}
```

To learn more about enums and type aliases, you can read the
To learn more about enums and type aliases, you can read the
[stabilization report][aliasreport] from when this feature was stabilized into
Rust.
Rust.

### See also:

[`match`][match], [`fn`][fn], and [`String`][str], []
[`match`][match], [`fn`][fn], and [`String`][str], ["Type alias enum variants" RFC][type_alias_rfc]

[c_struct]: https://en.wikipedia.org/wiki/Struct_(C_programming_language)
[match]: ../flow_control/match.md
[fn]: ../fn.md
[str]: ../std/str.md
[aliasreport]: https://github.com/rust-lang/rust/pull/61682/#issuecomment-502472847
[type_alias_rfc]: https://rust-lang.github.io/rfcs/2338-type-alias-enum-variants.html
4 changes: 2 additions & 2 deletions src/flow_control/match.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ fn main() {
// Match several values
2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
// Match an inclusive range
13...19 => println!("A teen"),
13..=19 => println!("A teen"),
// Handle the rest of cases
_ => println!("Ain't special"),
}
Expand All @@ -31,4 +31,4 @@ fn main() {
println!("{} -> {}", boolean, binary);
}
```
```
46 changes: 30 additions & 16 deletions src/fn/closures/capture.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,37 +18,51 @@ fn main() {
let color = "green";
// A closure to print `color` which immediately borrows (`&`)
// `color` and stores the borrow and closure in the `print`
// variable. It will remain borrowed until `print` goes out of
// scope. `println!` only requires `by reference` so it doesn't
// A closure to print `color` which immediately borrows (`&`) `color` and
// stores the borrow and closure in the `print` variable. It will remain
// borrowed until `print` is used the last time.
//
// `println!` only requires arguments by immutable reference so it doesn't
// impose anything more restrictive.
let print = || println!("`color`: {}", color);
// Call the closure using the borrow.
print();
// `color` can be borrowed immutably again, because the closure only holds
// an immutable reference to `color`.
let _reborrow = &color;
print();
let mut count = 0;
// A move or reborrow is allowed after the final use of `print`
let _color_moved = color;
// A closure to increment `count` could take either `&mut count`
// or `count` but `&mut count` is less restrictive so it takes
// that. Immediately borrows `count`.
let mut count = 0;
// A closure to increment `count` could take either `&mut count` or `count`
// but `&mut count` is less restrictive so it takes that. Immediately
// borrows `count`.
//
// A `mut` is required on `inc` because a `&mut` is stored inside.
// Thus, calling the closure mutates the closure which requires
// a `mut`.
// A `mut` is required on `inc` because a `&mut` is stored inside. Thus,
// calling the closure mutates the closure which requires a `mut`.
let mut inc = || {
count += 1;
println!("`count`: {}", count);
};
// Call the closure.
inc();
// Call the closure using a mutable borrow.
inc();
//let _reborrow = &mut count;
// The closure still mutably borrows `count` because it is called later.
// An attempt to reborrow will lead to an error.
// let _reborrow = &count;
// ^ TODO: try uncommenting this line.
inc();
// The closure no longer needs to borrow `&mut count`. Therefore, it is
// possible to reborrow without an error
let _count_reborrowed = &mut count;
// A non-copy type.
let movable = Box::new(3);
Expand All @@ -64,7 +78,7 @@ fn main() {
// `consume` consumes the variable so this can only be called once.
consume();
//consume();
// consume();
// ^ TODO: Try uncommenting this line.
}
```
Expand All @@ -82,7 +96,7 @@ fn main() {
println!("{}", contains(&1));
println!("{}", contains(&4));
// `println!("There're {} elements in vec", haystack.len());`
// println!("There're {} elements in vec", haystack.len());
// ^ Uncommenting above line will result in compile-time error
// because borrow checker doesn't allow re-using variable after it
// has been moved.
Expand Down
39 changes: 33 additions & 6 deletions src/fn/closures/closure_examples/iter_find.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Iterator::find
# Searching through iterators

`Iterator::find` is a function which when passed an iterator, will return
the first element which satisfies the predicate as an `Option`. Its
signature:
`Iterator::find` is a function which iterates over an iterator and searches for the
first value which satisfies some condition. If none of the values satisfy the
condition, it returns `None`. Its signature:

```rust,ignore
pub trait Iterator {
Expand All @@ -29,9 +29,11 @@ fn main() {
// `into_iter()` for vecs yields `i32`.
let mut into_iter = vec2.into_iter();
// A reference to what is yielded is `&&i32`. Destructure to `i32`.
// `iter()` for vecs yields `&i32`, and we want to reference one of its
// items, so we have to destructure `&&i32` to `i32`
println!("Find 2 in vec1: {:?}", iter .find(|&&x| x == 2));
// A reference to what is yielded is `&i32`. Destructure to `i32`.
// `into_iter()` for vecs yields `i32`, and we want to reference one of
// its items, so we have to destructure `&i32` to `i32`
println!("Find 2 in vec2: {:?}", into_iter.find(| &x| x == 2));
let array1 = [1, 2, 3];
Expand All @@ -44,8 +46,33 @@ fn main() {
}
```

`Iterator::find` gives you a reference to the item. But if you want the _index_ of the
item, use `Iterator::position`.

```rust,editable
fn main() {
let vec = vec![1, 9, 3, 3, 13, 2];
let index_of_first_even_number = vec.iter().position(|x| x % 2 == 0);
assert_eq!(index_of_first_even_number, Some(5));
let index_of_first_negative_number = vec.iter().position(|x| x < &0);
assert_eq!(index_of_first_negative_number, None);
}
```

### See also:

[`std::iter::Iterator::find`][find]

[`std::iter::Iterator::find_map`][find_map]

[`std::iter::Iterator::position`][position]

[`std::iter::Iterator::rposition`][rposition]

[find]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.find
[find_map]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.find_map
[position]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.position
[rposition]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.rposition
19 changes: 12 additions & 7 deletions src/fn/closures/output_parameters.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@ output parameters should also be possible. However, anonymous
closure types are, by definition, unknown, so we have to use
`impl Trait` to return them.

The valid traits for returns are slightly different than before:
The valid traits for returning a closure are:

* `Fn`: normal
* `FnMut`: normal
* `FnOnce`: There are some unusual things at play here, so the [`FnBox`][fnbox]
type is currently needed, and is unstable. This is expected to change in
the future.
* `Fn`
* `FnMut`
* `FnOnce`

Beyond this, the `move` keyword must be used, which signals that all captures
occur by value. This is required because any captures by reference would be
Expand All @@ -31,12 +29,20 @@ fn create_fnmut() -> impl FnMut() {
move || println!("This is a: {}", text)
}
fn create_fnonce() -> impl FnOnce() {
let text = "FnOnce".to_owned();
move || println!("This is a: {}", text)
}
fn main() {
let fn_plain = create_fn();
let mut fn_mut = create_fnmut();
let fn_once = create_fnonce();
fn_plain();
fn_mut();
fn_once();
}
```

Expand All @@ -46,6 +52,5 @@ fn main() {

[fn]: https://doc.rust-lang.org/std/ops/trait.Fn.html
[fnmut]: https://doc.rust-lang.org/std/ops/trait.FnMut.html
[fnbox]: https://doc.rust-lang.org/std/boxed/trait.FnBox.html
[generics]: ../../generics.md
[impltrait]: ../../trait/impl_trait.md
File renamed without changes.
File renamed without changes.

0 comments on commit e60b98d

Please sign in to comment.