mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 21:41:18 -06:00
501 lines
25 KiB
HTML
501 lines
25 KiB
HTML
<!DOCTYPE HTML>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title></title>
|
||
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
||
<meta name="description" content="{% block description %}{% endblock %}">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
|
||
<base href="">
|
||
|
||
<link rel="stylesheet" href="book.css">
|
||
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
|
||
|
||
<!-- Font Awesome -->
|
||
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
|
||
|
||
<link rel="stylesheet" href="highlight.css">
|
||
<link rel="stylesheet" href="tomorrow-night.css">
|
||
|
||
<!-- MathJax -->
|
||
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
|
||
|
||
<!-- Fetch JQuery from CDN but have a local fallback -->
|
||
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
|
||
<script>
|
||
if (typeof jQuery == 'undefined') {
|
||
document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
|
||
}
|
||
</script>
|
||
</head>
|
||
<body>
|
||
<!-- Set the theme before any content is loaded, prevents flash -->
|
||
<script type="text/javascript">
|
||
var theme = localStorage.getItem('theme');
|
||
if (theme == null) { theme = 'light'; }
|
||
$('body').removeClass().addClass(theme);
|
||
</script>
|
||
|
||
<!-- Hide / unhide sidebar before it is displayed -->
|
||
<script type="text/javascript">
|
||
var sidebar = localStorage.getItem('sidebar');
|
||
if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
|
||
else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
|
||
</script>
|
||
|
||
<div id="sidebar" class="sidebar">
|
||
<ul class="chapter"><li><a href="introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="hello-world.html"><strong>1.2.</strong> Hello, World!</a></li><li><a href="design.html"><strong>1.3.</strong> The Design of Rust</a></li></ul></li><li><a href="tutorial.html"><strong>2.</strong> Tutorial</a></li><li><a href="basics.html"><strong>3.</strong> The Basics</a></li><li><ul class="section"><li><a href="variable-bindings.html"><strong>3.1.</strong> Variable Bindings</a></li><li><a href="functions.html"><strong>3.2.</strong> Functions</a></li><li><a href="primitive-types.html"><strong>3.3.</strong> Primitive Types</a></li><li><a href="comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="if.html"><strong>3.5.</strong> `if`</a></li><li><a href="loops.html"><strong>3.6.</strong> Loops</a></li></ul></li><li><a href="ownership-and-borrowing.html"><strong>4.</strong> Ownership & borrowing</a></li><li><ul class="section"><li><a href="ownership.html"><strong>4.1.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong>4.2.</strong> References & Borrowing</a></li><li><a href="lifetimes.html"><strong>4.3.</strong> Lifetimes</a></li></ul></li><li><a href="basic-data-types.html"><strong>5.</strong> Basic Data Types</a></li><li><ul class="section"><li><a href="structs.html"><strong>5.1.</strong> Structs</a></li><li><a href="enums.html"><strong>5.2.</strong> Enums</a></li></ul></li><li><a href="crates-and-modules.html"><strong>6.</strong> Crates & Modules</a></li><li><a href="error-handling.html"><strong>7.</strong> Error Handling</a></li><li><a href="basic-collections.html"><strong>8.</strong> Basic Collections</a></li><li><ul class="section"><li><a href="vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="hashmap.html"><strong>8.3.</strong> `HashMap<K, V>`</a></li></ul></li><li><a href="traits.html"><strong>9.</strong> Traits</a></li><li><a href="closures.html" class="active"><strong>10.</strong> Closures</a></li><li><a href="iterators.html"><strong>11.</strong> Iterators</a></li><li><a href="io.html"><strong>12.</strong> I/O</a></li><li><ul class="section"><li><a href="read-and-write.html"><strong>12.1.</strong> `Read` & `Write`</a></li><li><a href="fs.html"><strong>12.2.</strong> `std::fs`</a></li><li><a href="path.html"><strong>12.3.</strong> `std::path`</a></li><li><a href="env.html"><strong>12.4.</strong> `std::env`</a></li></ul></li><li><a href="testing.html"><strong>13.</strong> Testing</a></li><li><a href="smart-pointers.html"><strong>14.</strong> Smart Pointers</a></li><li><ul class="section"><li><a href="deref.html"><strong>14.1.</strong> `Deref`</a></li><li><a href="deref-coercions.html"><strong>14.2.</strong> `Deref` coercions</a></li><li><a href="box.html"><strong>14.3.</strong> `Box<T>`</a></li><li><a href="rc.html"><strong>14.4.</strong> `Rc<T>`</a></li></ul></li><li><a href="concurrency.html"><strong>15.</strong> Concurrency</a></li><li><ul class="section"><li><a href="threads.html"><strong>15.1.</strong> Threads</a></li><li><a href="send-and-sync.html"><strong>15.2.</strong> `Send` & `Sync`</a></li><li><a href="arc.html"><strong>15.3.</strong> `Arc<T>`</a></li><li><a href="mutex.html"><strong>15.4.</strong> `Mutex<T>`</a></li><li><a href="channels.html"><strong>15.5.</strong> `Channels`</a></li></ul></li><li><a href="unsafe-rust.html"><strong>16.</strong> Unsafe Rust</a></li><li><ul class="section"><li><a href="raw-pointers.html"><strong>16.1.</strong> Raw Pointers</a></li><li><a href="transmute.html"><strong>16.2.</strong> transmute</a></li></ul></li><li><a href="ffi.html"><strong>17.</strong> FFI</a></li><li><ul class="section"><li><a href="conditional-compilation.html"><strong>17.1.</strong> Conditional Compilation</a></li><li><a href="bindings-to-c.html"><strong>17.2.</strong> Bindings to C</a></li><li><a href="using-rust-from-other-languages.html"><strong>17.3.</strong> Using Rust from Other Languages</a></li><li><a href="static.html"><strong>17.4.</strong> `static`</a></li></ul></li><li><a href="cargo.html"><strong>18.</strong> Cargo</a></li><li><ul class="section"><li><a href="cratesio.html"><strong>18.1.</strong> Crates.io</a></li></ul></li><li><a href="advanced-type-system-features.html"><strong>19.</strong> Advanced Type System Features</a></li><li><ul class="section"><li><a href="associated-types.html"><strong>19.1.</strong> Associated Types</a></li><li><a href="trait-objects.html"><strong>19.2.</strong> Trait Objects</a></li><li><a href="ufcs.html"><strong>19.3.</strong> UFCS</a></li><li><a href="coherence.html"><strong>19.4.</strong> Coherence</a></li></ul></li><li><a href="interior-mutability.html"><strong>20.</strong> Interior mutability</a></li><li><ul class="section"><li><a href="cell.html"><strong>20.1.</strong> `Cell<T>`</a></li><li><a href="refcell.html"><strong>20.2.</strong> `RefCell<T>`</a></li></ul></li><li><a href="macros.html"><strong>21.</strong> Macros</a></li><li><a href="nightly-rust.html"><strong>22.</strong> Nightly Rust</a></li></ul>
|
||
</div>
|
||
|
||
<div id="page-wrapper" class="page-wrapper">
|
||
|
||
<div class="page">
|
||
<div id="menu-bar" class="menu-bar">
|
||
<div class="left-buttons">
|
||
<i id="sidebar-toggle" class="fa fa-bars"></i>
|
||
<i id="theme-toggle" class="fa fa-paint-brush"></i>
|
||
</div>
|
||
|
||
<h1 class="menu-title"></h1>
|
||
|
||
<div class="right-buttons">
|
||
<i id="print-button" class="fa fa-print" title="Print this book"></i>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="content" class="content">
|
||
<h1>Closures</h1>
|
||
<p>Sometimes it is useful to wrap up a function and <em>free variables</em> for better
|
||
clarity and reuse. The free variables that can be used come from the
|
||
enclosing scope and are ‘closed over’ when used in the function. From this, we
|
||
get the name ‘closures’ and Rust provides a really great implementation of
|
||
them, as we’ll see.</p>
|
||
<h1>Syntax</h1>
|
||
<p>Closures look like this:</p>
|
||
<pre><code class="language-rust">let plus_one = |x: i32| x + 1;
|
||
|
||
assert_eq!(2, plus_one(1));
|
||
</code></pre>
|
||
<p>We create a binding, <code>plus_one</code>, and assign it to a closure. The closure’s
|
||
arguments go between the pipes (<code>|</code>), and the body is an expression, in this
|
||
case, <code>x + 1</code>. Remember that <code>{ }</code> is an expression, so we can have multi-line
|
||
closures too:</p>
|
||
<pre><code class="language-rust">let plus_two = |x| {
|
||
let mut result: i32 = x;
|
||
|
||
result += 1;
|
||
result += 1;
|
||
|
||
result
|
||
};
|
||
|
||
assert_eq!(4, plus_two(2));
|
||
</code></pre>
|
||
<p>You’ll notice a few things about closures that are a bit different from regular
|
||
named functions defined with <code>fn</code>. The first is that we did not need to
|
||
annotate the types of arguments the closure takes or the values it returns. We
|
||
can:</p>
|
||
<pre><code class="language-rust">let plus_one = |x: i32| -> i32 { x + 1 };
|
||
|
||
assert_eq!(2, plus_one(1));
|
||
</code></pre>
|
||
<p>But we don’t have to. Why is this? Basically, it was chosen for ergonomic
|
||
reasons. While specifying the full type for named functions is helpful with
|
||
things like documentation and type inference, the full type signatures of
|
||
closures are rarely documented since they’re anonymous, and they don’t cause
|
||
the kinds of error-at-a-distance problems that inferring named function types
|
||
can.</p>
|
||
<p>The second is that the syntax is similar, but a bit different. I’ve added
|
||
spaces here for easier comparison:</p>
|
||
<pre><code class="language-rust">fn plus_one_v1 (x: i32) -> i32 { x + 1 }
|
||
let plus_one_v2 = |x: i32| -> i32 { x + 1 };
|
||
let plus_one_v3 = |x: i32| x + 1 ;
|
||
</code></pre>
|
||
<p>Small differences, but they’re similar.</p>
|
||
<h1>Closures and their environment</h1>
|
||
<p>The environment for a closure can include bindings from its enclosing scope in
|
||
addition to parameters and local bindings. It looks like this:</p>
|
||
<pre><code class="language-rust">let num = 5;
|
||
let plus_num = |x: i32| x + num;
|
||
|
||
assert_eq!(10, plus_num(5));
|
||
</code></pre>
|
||
<p>This closure, <code>plus_num</code>, refers to a <code>let</code> binding in its scope: <code>num</code>. More
|
||
specifically, it borrows the binding. If we do something that would conflict
|
||
with that binding, we get an error. Like this one:</p>
|
||
<pre><code class="language-rust,ignore">let mut num = 5;
|
||
let plus_num = |x: i32| x + num;
|
||
|
||
let y = &mut num;
|
||
</code></pre>
|
||
<p>Which errors with:</p>
|
||
<pre><code class="language-text">error: cannot borrow `num` as mutable because it is also borrowed as immutable
|
||
let y = &mut num;
|
||
^~~
|
||
note: previous borrow of `num` occurs here due to use in closure; the immutable
|
||
borrow prevents subsequent moves or mutable borrows of `num` until the borrow
|
||
ends
|
||
let plus_num = |x| x + num;
|
||
^~~~~~~~~~~
|
||
note: previous borrow ends here
|
||
fn main() {
|
||
let mut num = 5;
|
||
let plus_num = |x| x + num;
|
||
|
||
let y = &mut num;
|
||
}
|
||
^
|
||
</code></pre>
|
||
<p>A verbose yet helpful error message! As it says, we can’t take a mutable borrow
|
||
on <code>num</code> because the closure is already borrowing it. If we let the closure go
|
||
out of scope, we can:</p>
|
||
<pre><code class="language-rust">let mut num = 5;
|
||
{
|
||
let plus_num = |x: i32| x + num;
|
||
|
||
} // plus_num goes out of scope, borrow of num ends
|
||
|
||
let y = &mut num;
|
||
</code></pre>
|
||
<p>If your closure requires it, however, Rust will take ownership and move
|
||
the environment instead. This doesn’t work:</p>
|
||
<pre><code class="language-rust,ignore">let nums = vec![1, 2, 3];
|
||
|
||
let takes_nums = || nums;
|
||
|
||
println!("{:?}", nums);
|
||
</code></pre>
|
||
<p>We get this error:</p>
|
||
<pre><code class="language-text">note: `nums` moved into closure environment here because it has type
|
||
`[closure(()) -> collections::vec::Vec<i32>]`, which is non-copyable
|
||
let takes_nums = || nums;
|
||
^~~~~~~
|
||
</code></pre>
|
||
<p><code>Vec<T></code> has ownership over its contents, and therefore, when we refer to it
|
||
in our closure, we have to take ownership of <code>nums</code>. It’s the same as if we’d
|
||
passed <code>nums</code> to a function that took ownership of it.</p>
|
||
<h2><code>move</code> closures</h2>
|
||
<p>We can force our closure to take ownership of its environment with the <code>move</code>
|
||
keyword:</p>
|
||
<pre><code class="language-rust">let num = 5;
|
||
|
||
let owns_num = move |x: i32| x + num;
|
||
</code></pre>
|
||
<p>Now, even though the keyword is <code>move</code>, the variables follow normal move semantics.
|
||
In this case, <code>5</code> implements <code>Copy</code>, and so <code>owns_num</code> takes ownership of a copy
|
||
of <code>num</code>. So what’s the difference?</p>
|
||
<pre><code class="language-rust">let mut num = 5;
|
||
|
||
{
|
||
let mut add_num = |x: i32| num += x;
|
||
|
||
add_num(5);
|
||
}
|
||
|
||
assert_eq!(10, num);
|
||
</code></pre>
|
||
<p>So in this case, our closure took a mutable reference to <code>num</code>, and then when
|
||
we called <code>add_num</code>, it mutated the underlying value, as we’d expect. We also
|
||
needed to declare <code>add_num</code> as <code>mut</code> too, because we’re mutating its
|
||
environment.</p>
|
||
<p>If we change to a <code>move</code> closure, it’s different:</p>
|
||
<pre><code class="language-rust">let mut num = 5;
|
||
|
||
{
|
||
let mut add_num = move |x: i32| num += x;
|
||
|
||
add_num(5);
|
||
}
|
||
|
||
assert_eq!(5, num);
|
||
</code></pre>
|
||
<p>We only get <code>5</code>. Rather than taking a mutable borrow out on our <code>num</code>, we took
|
||
ownership of a copy.</p>
|
||
<p>Another way to think about <code>move</code> closures: they give a closure its own stack
|
||
frame. Without <code>move</code>, a closure may be tied to the stack frame that created
|
||
it, while a <code>move</code> closure is self-contained. This means that you cannot
|
||
generally return a non-<code>move</code> closure from a function, for example.</p>
|
||
<p>But before we talk about taking and returning closures, we should talk some
|
||
more about the way that closures are implemented. As a systems language, Rust
|
||
gives you tons of control over what your code does, and closures are no
|
||
different.</p>
|
||
<h1>Closure implementation</h1>
|
||
<p>Rust’s implementation of closures is a bit different than other languages. They
|
||
are effectively syntax sugar for traits. You’ll want to make sure to have read
|
||
the <a href="traits.html">traits chapter</a> before this one, as well as the chapter on <a href="trait-objects.html">trait
|
||
objects</a>.</p>
|
||
<p>Got all that? Good.</p>
|
||
<p>The key to understanding how closures work under the hood is something a bit
|
||
strange: Using <code>()</code> to call a function, like <code>foo()</code>, is an overloadable
|
||
operator. From this, everything else clicks into place. In Rust, we use the
|
||
trait system to overload operators. Calling functions is no different. We have
|
||
three separate traits to overload with:</p>
|
||
<pre><code class="language-rust"># mod foo {
|
||
pub trait Fn<Args> : FnMut<Args> {
|
||
extern "rust-call" fn call(&self, args: Args) -> Self::Output;
|
||
}
|
||
|
||
pub trait FnMut<Args> : FnOnce<Args> {
|
||
extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
|
||
}
|
||
|
||
pub trait FnOnce<Args> {
|
||
type Output;
|
||
|
||
extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
|
||
}
|
||
# }
|
||
</code></pre>
|
||
<p>You’ll notice a few differences between these traits, but a big one is <code>self</code>:
|
||
<code>Fn</code> takes <code>&self</code>, <code>FnMut</code> takes <code>&mut self</code>, and <code>FnOnce</code> takes <code>self</code>. This
|
||
covers all three kinds of <code>self</code> via the usual method call syntax. But we’ve
|
||
split them up into three traits, rather than having a single one. This gives us
|
||
a large amount of control over what kind of closures we can take.</p>
|
||
<p>The <code>|| {}</code> syntax for closures is sugar for these three traits. Rust will
|
||
generate a struct for the environment, <code>impl</code> the appropriate trait, and then
|
||
use it.</p>
|
||
<h1>Taking closures as arguments</h1>
|
||
<p>Now that we know that closures are traits, we already know how to accept and
|
||
return closures: just like any other trait!</p>
|
||
<p>This also means that we can choose static vs dynamic dispatch as well. First,
|
||
let’s write a function which takes something callable, calls it, and returns
|
||
the result:</p>
|
||
<pre><code class="language-rust">fn call_with_one<F>(some_closure: F) -> i32
|
||
where F : Fn(i32) -> i32 {
|
||
|
||
some_closure(1)
|
||
}
|
||
|
||
let answer = call_with_one(|x| x + 2);
|
||
|
||
assert_eq!(3, answer);
|
||
</code></pre>
|
||
<p>We pass our closure, <code>|x| x + 2</code>, to <code>call_with_one</code>. It just does what it
|
||
suggests: it calls the closure, giving it <code>1</code> as an argument.</p>
|
||
<p>Let’s examine the signature of <code>call_with_one</code> in more depth:</p>
|
||
<pre><code class="language-rust">fn call_with_one<F>(some_closure: F) -> i32
|
||
# where F : Fn(i32) -> i32 {
|
||
# some_closure(1) }
|
||
</code></pre>
|
||
<p>We take one parameter, and it has the type <code>F</code>. We also return a <code>i32</code>. This part
|
||
isn’t interesting. The next part is:</p>
|
||
<pre><code class="language-rust"># fn call_with_one<F>(some_closure: F) -> i32
|
||
where F : Fn(i32) -> i32 {
|
||
# some_closure(1) }
|
||
</code></pre>
|
||
<p>Because <code>Fn</code> is a trait, we can bound our generic with it. In this case, our
|
||
closure takes a <code>i32</code> as an argument and returns an <code>i32</code>, and so the generic
|
||
bound we use is <code>Fn(i32) -> i32</code>.</p>
|
||
<p>There’s one other key point here: because we’re bounding a generic with a
|
||
trait, this will get monomorphized, and therefore, we’ll be doing static
|
||
dispatch into the closure. That’s pretty neat. In many languages, closures are
|
||
inherently heap allocated, and will always involve dynamic dispatch. In Rust,
|
||
we can stack allocate our closure environment, and statically dispatch the
|
||
call. This happens quite often with iterators and their adapters, which often
|
||
take closures as arguments.</p>
|
||
<p>Of course, if we want dynamic dispatch, we can get that too. A trait object
|
||
handles this case, as usual:</p>
|
||
<pre><code class="language-rust">fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 {
|
||
some_closure(1)
|
||
}
|
||
|
||
let answer = call_with_one(&|x| x + 2);
|
||
|
||
assert_eq!(3, answer);
|
||
</code></pre>
|
||
<p>Now we take a trait object, a <code>&Fn</code>. And we have to make a reference
|
||
to our closure when we pass it to <code>call_with_one</code>, so we use <code>&||</code>.</p>
|
||
<h1>Function pointers and closures</h1>
|
||
<p>A function pointer is kind of like a closure that has no environment. As such,
|
||
you can pass a function pointer to any function expecting a closure argument,
|
||
and it will work:</p>
|
||
<pre><code class="language-rust">fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 {
|
||
some_closure(1)
|
||
}
|
||
|
||
fn add_one(i: i32) -> i32 {
|
||
i + 1
|
||
}
|
||
|
||
let f = add_one;
|
||
|
||
let answer = call_with_one(&f);
|
||
|
||
assert_eq!(2, answer);
|
||
</code></pre>
|
||
<p>In this example, we don’t strictly need the intermediate variable <code>f</code>,
|
||
the name of the function works just fine too:</p>
|
||
<pre><code class="language-ignore">let answer = call_with_one(&add_one);
|
||
</code></pre>
|
||
<h1>Returning closures</h1>
|
||
<p>It’s very common for functional-style code to return closures in various
|
||
situations. If you try to return a closure, you may run into an error. At
|
||
first, it may seem strange, but we’ll figure it out. Here’s how you’d probably
|
||
try to return a closure from a function:</p>
|
||
<pre><code class="language-rust,ignore">fn factory() -> (Fn(i32) -> i32) {
|
||
let num = 5;
|
||
|
||
|x| x + num
|
||
}
|
||
|
||
let f = factory();
|
||
|
||
let answer = f(1);
|
||
assert_eq!(6, answer);
|
||
</code></pre>
|
||
<p>This gives us these long, related errors:</p>
|
||
<pre><code class="language-text">error: the trait `core::marker::Sized` is not implemented for the type
|
||
`core::ops::Fn(i32) -> i32` [E0277]
|
||
fn factory() -> (Fn(i32) -> i32) {
|
||
^~~~~~~~~~~~~~~~
|
||
note: `core::ops::Fn(i32) -> i32` does not have a constant size known at compile-time
|
||
fn factory() -> (Fn(i32) -> i32) {
|
||
^~~~~~~~~~~~~~~~
|
||
error: the trait `core::marker::Sized` is not implemented for the type `core::ops::Fn(i32) -> i32` [E0277]
|
||
let f = factory();
|
||
^
|
||
note: `core::ops::Fn(i32) -> i32` does not have a constant size known at compile-time
|
||
let f = factory();
|
||
^
|
||
</code></pre>
|
||
<p>In order to return something from a function, Rust needs to know what
|
||
size the return type is. But since <code>Fn</code> is a trait, it could be various
|
||
things of various sizes: many different types can implement <code>Fn</code>. An easy
|
||
way to give something a size is to take a reference to it, as references
|
||
have a known size. So we’d write this:</p>
|
||
<pre><code class="language-rust,ignore">fn factory() -> &(Fn(i32) -> i32) {
|
||
let num = 5;
|
||
|
||
|x| x + num
|
||
}
|
||
|
||
let f = factory();
|
||
|
||
let answer = f(1);
|
||
assert_eq!(6, answer);
|
||
</code></pre>
|
||
<p>But we get another error:</p>
|
||
<pre><code class="language-text">error: missing lifetime specifier [E0106]
|
||
fn factory() -> &(Fn(i32) -> i32) {
|
||
^~~~~~~~~~~~~~~~~
|
||
</code></pre>
|
||
<p>Right. Because we have a reference, we need to give it a lifetime. But
|
||
our <code>factory()</code> function takes no arguments, so
|
||
<a href="lifetimes.html#lifetime-elision">elision</a> doesn’t kick in here. Then what
|
||
choices do we have? Try <code>'static</code>:</p>
|
||
<pre><code class="language-rust,ignore">fn factory() -> &'static (Fn(i32) -> i32) {
|
||
let num = 5;
|
||
|
||
|x| x + num
|
||
}
|
||
|
||
let f = factory();
|
||
|
||
let answer = f(1);
|
||
assert_eq!(6, answer);
|
||
</code></pre>
|
||
<p>But we get another error:</p>
|
||
<pre><code class="language-text">error: mismatched types:
|
||
expected `&'static core::ops::Fn(i32) -> i32`,
|
||
found `[closure@<anon>:7:9: 7:20]`
|
||
(expected &-ptr,
|
||
found closure) [E0308]
|
||
|x| x + num
|
||
^~~~~~~~~~~
|
||
|
||
</code></pre>
|
||
<p>This error is letting us know that we don’t have a <code>&'static Fn(i32) -> i32</code>,
|
||
we have a <code>[closure@<anon>:7:9: 7:20]</code>. Wait, what?</p>
|
||
<p>Because each closure generates its own environment <code>struct</code> and implementation
|
||
of <code>Fn</code> and friends, these types are anonymous. They exist just solely for
|
||
this closure. So Rust shows them as <code>closure@<anon></code>, rather than some
|
||
autogenerated name.</p>
|
||
<p>The error also points out that the return type is expected to be a reference,
|
||
but what we are trying to return is not. Further, we cannot directly assign a
|
||
<code>'static</code> lifetime to an object. So we'll take a different approach and return
|
||
a ‘trait object’ by <code>Box</code>ing up the <code>Fn</code>. This <em>almost</em> works:</p>
|
||
<pre><code class="language-rust,ignore">fn factory() -> Box<Fn(i32) -> i32> {
|
||
let num = 5;
|
||
|
||
Box::new(|x| x + num)
|
||
}
|
||
# fn main() {
|
||
let f = factory();
|
||
|
||
let answer = f(1);
|
||
assert_eq!(6, answer);
|
||
# }
|
||
</code></pre>
|
||
<p>There’s just one last problem:</p>
|
||
<pre><code class="language-text">error: closure may outlive the current function, but it borrows `num`,
|
||
which is owned by the current function [E0373]
|
||
Box::new(|x| x + num)
|
||
^~~~~~~~~~~
|
||
</code></pre>
|
||
<p>Well, as we discussed before, closures borrow their environment. And in this
|
||
case, our environment is based on a stack-allocated <code>5</code>, the <code>num</code> variable
|
||
binding. So the borrow has a lifetime of the stack frame. So if we returned
|
||
this closure, the function call would be over, the stack frame would go away,
|
||
and our closure is capturing an environment of garbage memory! With one last
|
||
fix, we can make this work:</p>
|
||
<pre><code class="language-rust">fn factory() -> Box<Fn(i32) -> i32> {
|
||
let num = 5;
|
||
|
||
Box::new(move |x| x + num)
|
||
}
|
||
# fn main() {
|
||
let f = factory();
|
||
|
||
let answer = f(1);
|
||
assert_eq!(6, answer);
|
||
# }
|
||
</code></pre>
|
||
<p>By making the inner closure a <code>move Fn</code>, we create a new stack frame for our
|
||
closure. By <code>Box</code>ing it up, we’ve given it a known size, and allowing it to
|
||
escape our stack frame.</p>
|
||
|
||
</div>
|
||
|
||
<!-- Mobile navigation buttons -->
|
||
|
||
<a href="traits.html" class="mobile-nav-chapters previous">
|
||
<i class="fa fa-angle-left"></i>
|
||
</a>
|
||
|
||
|
||
|
||
<a href="iterators.html" class="mobile-nav-chapters next">
|
||
<i class="fa fa-angle-right"></i>
|
||
</a>
|
||
|
||
|
||
</div>
|
||
|
||
|
||
<a href="traits.html" class="nav-chapters previous">
|
||
<i class="fa fa-angle-left"></i>
|
||
</a>
|
||
|
||
|
||
|
||
<a href="iterators.html" class="nav-chapters next">
|
||
<i class="fa fa-angle-right"></i>
|
||
</a>
|
||
|
||
|
||
</div>
|
||
|
||
|
||
<!-- Local fallback for Font Awesome -->
|
||
<script>
|
||
if ($(".fa").css("font-family") !== "FontAwesome") {
|
||
$('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
|
||
}
|
||
</script>
|
||
|
||
<script src="highlight.js"></script>
|
||
<script src="book.js"></script>
|
||
</body>
|
||
</html>
|