What does Box<Fn() + Send + 'static>
mean in rust?
I stumbled upon this syntax while reading advanced types chapter. Send
is a trait but what does it mean to +
a lifetime to a trait ('static
in this case) in type parametrization ? Also what is Fn()
?
A static item is similar to a constant, except that it represents a precise memory location in the program. A static is never "inlined" at the usage site, and all references to it refer to the same memory location. Static items have the static lifetime, which outlives all other lifetimes in a Rust program.
A trait object is an opaque value of another type that implements a set of traits. The set of traits is made up of an object safe base trait plus any number of auto traits. Trait objects implement the base trait, its auto traits, and any supertraits of the base trait.
Let's decompose it one-by-one.
Box<T>
is a pointer to heap-allocated T
. We use it here because trait objects can only exist behind pointers.
In Box<Fn() + Send + 'static>
, Fn() + Send + 'static
is a trait object type. In future, it will be written Box<dyn (Fn() + Send + 'static)>
to avoid confusion.
Inside dyn
are restrictions to the original type. Box<T>
can be coerced into Box<Fn() + Send + 'static>
only when T: Fn() + Send + 'static
. Therefore, although we don't know the original type, we can assume it was Fn()
and Send
and had 'static
lifetime.
Fn()
This is a trait, just like Clone
or Default
. However, it uses a special syntax sugar.
Fn(A1, ..., An)
is a syntax sugar for Fn<(A1, ..., An), Output=()>
.Fn(A1, ..., An) -> R
is a syntax sugar for Fn<(A1, ..., An), Output=R>
.Fn
, FnMut
, FnOnce
, and FnBox
.So what does Fn
mean? T: Fn(A1, ..., An) -> R
means x: T
is a callable object with arguments A1, ..., An
and return type R
. Examples include function pointers and closures.
Send
means that values of this type can be sent across threads. Since this is an auto trait, it can be specified as the second bounds of dyn
types (trait object types).
'static
boundIn fact, dyn
types (trait object types) must have exactly one lifetime bound. It's inferred when omitted. The inference rule is described in RFC 0192 and RFC 1156. It's basically as follows:
Box<Any>
is Box<Any + 'static>
because Any: 'static
.&'a Fn()
is &'a (Fn() + 'a)
.'static
(for a function signature) or an anonymous lifetime (for a function body).f: Box<Fn() + Send + 'static>
is an owned pointer to a callable value (with the original type unknown and dynamically change) such as closures (with no argument or no return value), which can be sent across threads and lives as long as the program itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With