Trait std::marker::PhantomFnStable
[-] [+]
[src]
pub trait PhantomFn<A, R = ()> where A: ?Sized, R: ?Sized { }
PhantomFn
is a marker trait for use with traits that contain
type or lifetime parameters that do not appear in any of their
methods. In that case, you can either remove those parameters, or
add a PhantomFn
supertrait that reflects the signature of
methods that compiler should "pretend" exists. This most commonly
occurs for traits with no methods: in that particular case, you
can extend MarkerTrait
, which is equivalent to
PhantomFn<Self>
.
Example
As an example, consider a trait with no methods like Even
, meant
to represent types that are "even":
trait Even { }
In this case, because the implicit parameter Self
is unused, the
compiler will issue an error. The only purpose of this trait is to
categorize types (and hence instances of those types) as "even" or
not, so if we were going to have a method, it might look like:
trait Even { fn is_even(self) -> bool { true } }
Therefore, we can model a method like this as follows:
fn main() { use std::marker::PhantomFn; trait Even : PhantomFn<Self> { } }use std::marker::PhantomFn; trait Even : PhantomFn<Self> { }
Another equivalent, but clearer, option would be to use
MarkerTrait
:
use std::marker::MarkerTrait; trait Even : MarkerTrait { }
Parameters
A
represents the type of the method's argument. You can use a tuple to represent "multiple" arguments. Any types appearing here will be considered "contravariant".R
, if supplied, represents the method's return type. This defaults to()
as it is rarely needed.
Additional reading
More details and background can be found in RFC 738.