Understanding Closures in Rust.

Andrew Pritchard
The Startup
Published in
6 min readJun 25, 2019

--

Summary

  • Closures are a combination of a function pointer (fn) and a context.
  • A closure with no context is just a function pointer.
  • A closure which has an immutable context belongs to Fn.
  • A closure which has a mutable context belongs to FnMut.
  • A closure that owns its context belongs to FnOnce.

Understanding the different types of closures in Rust.

Unlike some other languages, Rust is explicit about our use of the self parameter. We have to specify self to be the first parameter of a function signature when we are implementing a struct:

struct MyStruct {
text: &'static str,
number: u32,
}
impl MyStruct {
fn new (text: &'static str, number: u32) -> MyStruct {
MyStruct {
text: text,
number: number,
}
}
// We have to specify that 'self' is an argument.
fn get_number (&self) -> u32 {
self.number
}
// We can specify different kinds of ownership and mutability of self.
fn inc_number (&mut self) {
self.number += 1;
}
// There are three different types of 'self'
fn destructor (self) {
println!("Destructing {}"

--

--

Andrew Pritchard
The Startup

The stories I write are a part of a learning journey through life, logic and programming. Share this journey with me.