Struct std::kinds::marker::ContravariantTypeExperimental
[-]
[+]
[src]
pub struct ContravariantType<T>;
A marker type whose type parameter T
is considered to be
contravariant with respect to the type itself. This is (typically)
used to indicate that an instance of the type T
will be consumed
(but not read from), even though that may not be apparent.
For more information about variance, refer to this Wikipedia article http://en.wikipedia.org/wiki/Variance_%28computer_science%29.
Note: It is very unusual to have to add a contravariant constraint.
If you are not sure, you probably want to use InvariantType
.
Example
Given a struct S
that includes a type parameter T
but does not actually reference that type parameter:
use std::mem; struct S<T> { x: *const () } fn get<T>(s: &S<T>, v: T) { unsafe { let x: fn(T) = mem::transmute(s.x); x(v) } }
The type system would currently infer that the value of
the type parameter T
is irrelevant, and hence a S<int>
is
a subtype of S<Box<int>>
(or, for that matter, S<U>
for
any U
). But this is incorrect because get()
converts the
*()
into a fn(T)
and then passes a value of type T
to it.
Supplying a ContravariantType
marker would correct the
problem, because it would mark S
so that S<T>
is only a
subtype of S<U>
if U
is a subtype of T
; given that the
function requires arguments of type T
, it must also accept
arguments of type U
, hence such a conversion is safe.