Skip to content

Commit

Permalink
WIP Closures1
Browse files Browse the repository at this point in the history
  • Loading branch information
junderw committed Sep 2, 2024
1 parent bc3808c commit 4c80d7b
Show file tree
Hide file tree
Showing 4 changed files with 101 additions and 0 deletions.
25 changes: 25 additions & 0 deletions exercises/18_closures/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Closures

Closures in Rust are anonymous functions that can capture variables from their surrounding environment. They are similar to lambda expressions or anonymous functions in other languages like Python or JavaScript, but with a few key differences that stem from Rust's ownership system and its focus on safety and performance.

## How Closures Work in Rust

In Rust, closures are defined using the pipe syntax (ie. `|x: String|`) to enclose their parameters and are generally more flexible than functions because they can capture variables from their environment in three different ways:

By Shared Reference (`&T`): Borrowing values from the environment without taking ownership.
By Exclusive Reference (`&mut T`): Mutably borrowing values, allowing them to be modified.
By Value (`T`): Taking ownership of the values, which can be moved into the closure.
This flexibility allows closures to be used in a variety of contexts, such as iterators, where they can efficiently process data streams without the overhead of function calls. Rust's closures can also implement one of the three `Fn`, `FnMut`, or `FnOnce` traits, depending on how they capture their environment, which makes them highly adaptable for various use cases.

## Comparison to Other Languages

Unlike higher-level languages where closures often simply reference variables from their enclosing scope, Rust's closures need to conform to strict ownership and borrowing rules. This ensures memory safety but also introduces complexities not found in more dynamic languages. For example, deciding whether a closure should move or borrow variables can be non-trivial, especially when dealing with mutable or non-`Copy` types.

## Common Challenges

One of the challenges with closures in Rust is understanding how they capture variables and the implications for the borrow checker. For instance, if a closure moves a variable, that variable is no longer accessible after the closure is called, which can lead to borrow checker errors that might confuse newcomers. Additionally, because closures in Rust can sometimes have complex types (especially when capturing environment variables), they often require type annotations or explicit trait bounds when used in generic contexts.

## Further information

- [The Rust Book](https://doc.rust-lang.org/stable/book/ch13-01-closures.html)
- [Rust By Example](https://doc.rust-lang.org/rust-by-example/fn/closures.html)
64 changes: 64 additions & 0 deletions exercises/18_closures/closures1.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// closures1.rs
//
// "Why do we even need closures?" is a question that gets asked from time to time.
// While it's true that most things that closures can do can also be done with
// regular old structs and enums, closures can make things a lot more clear with a lot
// less clutter compared to structs.
//
// Below is a good example of how one could implement a capturing closure using structs,
// and how closures simplifies this greatly.
//
// Execute `rustlings hint closures1` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE


trait Doorman {
fn greet_customer(&self, customer_name: &str);
}

struct GreeterWithState<'a> {
greeting: &'a str,
}

impl Doorman for GreeterWithState<'_> {
fn greet_customer(&self, customer_name: &str) {
println!("{}, {}?", self.greeting, customer_name);
}
}

fn greet_customers(doorman: impl Doorman) {
doorman.greet_customer("Bill");
doorman.greet_customer("Alex");
doorman.greet_customer("John");
doorman.greet_customer("Jessie");
}

fn greet_customers_closure(doorman: impl Fn(&str)) {
doorman("Bill");
doorman("Alex");
doorman("John");
doorman("Jessie");
}

fn main() {
let greeting = String::from("Hello! How are you");

// Method 1 for passing in functions with state.
// Just create a struct, store the state, and add a method.
// If you need to be generic, it can be a trait method.
let doorman = GreeterWithState {
greeting: &greeting,
};
greet_customers(doorman);

// Method 2 for passing in functions with state.
// Notice that the body of this closure is exactly the same
// as GreeterWithState's Doorman implementation.
//
// This makes things much cleaner with less clutter, but
// we are forgetting something very important.
greet_customers_closure(|customer_name| {
println!("{}, {}?", self.greeting, customer_name); // TODO: Only modify this line
})
}
1 change: 1 addition & 0 deletions exercises/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
| traits | §10.2 |
| tests | §11.1 |
| lifetimes | §10.3 |
| closures | §13.1 |
| iterators | §13.2-4 |
| threads | §16.1-3 |
| smart_pointers | §15, §16.3 |
Expand Down
11 changes: 11 additions & 0 deletions info.toml
Original file line number Diff line number Diff line change
Expand Up @@ -932,6 +932,17 @@ To handle that you need to add a special attribute to the test function.
You can refer to the docs:
https://doc.rust-lang.org/stable/book/ch11-01-writing-tests.html#checking-for-panics-with-should_panic"""

# CLOSURES

[[exercises]]
name = "closures1"
path = "exercises/18_closures/closures1.rs"
mode = "compile"
hint = """
Self is a concept that is only used in struct/enum methods.
Closures in Rust do not have a self to refer to, unlike other languages that might use this or self."""

# STANDARD LIBRARY TYPES

[[exercises]]
Expand Down

0 comments on commit 4c80d7b

Please sign in to comment.