Trait spidermeme::SameTypeAs[][src]

pub trait SameTypeAs<T>: SameTypeAs<T> { }
Expand description

SameTypeAs<T> is a marker trait that is automatically implemented for all types that alias to the same type T. Lifetimes are not considered.

Examples

use spidermeme::SameTypeAs;
use static_assertions::{assert_impl_all, assert_not_impl_any};

assert_impl_all!(i32: SameTypeAs<i32>);
assert_not_impl_any!(i32: SameTypeAs<f64>);

Different types with identical structures aren’t equal:

use spidermeme::SameTypeAs;
use static_assertions::{assert_impl_all, assert_not_impl_any};

struct A(i32);
struct B(i32);

assert_impl_all!(A: SameTypeAs<A>);
assert_not_impl_any!(A: SameTypeAs<B>);

Type aliases should work as expected:

use spidermeme::SameTypeAs;
use static_assertions::{assert_impl_all, assert_not_impl_any};

type AliasOfI32 = i32;

assert_impl_all!(AliasOfI32: SameTypeAs<i32>);
assert_not_impl_any!(AliasOfI32: SameTypeAs<i64>);

Generics should work too:

use spidermeme::SameTypeAs;
use static_assertions::{assert_impl_all, assert_not_impl_any};
use std::marker::PhantomData;

struct Generic<T>(PhantomData<T>);

assert_impl_all!(Generic<i32>: SameTypeAs<Generic<i32>>);
assert_not_impl_any!(Generic<i32>: SameTypeAs<Generic<f64>>);

Different kinds of references should work too:

use spidermeme::SameTypeAs;

struct Pair<T1, T2>(T1, T2);

trait Heterogeneous {
    fn is_same(&self) -> bool;
}
impl<T1, T2> Heterogeneous for Pair<T1, T2> {
    fn is_same(&self) -> bool { false }
}
impl<T1, T2> Pair<T1, T2> where T1: SameTypeAs<T2> {
    fn is_same(&self) -> bool { true }
}

let x: i32 = 1;
let mut y: i32 = 1;
let same = Pair(&x, &x);
let different = Pair(&x, &mut y);

assert!(same.is_same());
assert!(!different.is_same());

Different lifetimes don’t make them different. The following two examples do compile:

use spidermeme::SameTypeAs;

struct Generic<'a, 'b>(&'a(), &'b()) where &'a(): SameTypeAs<&'b()>;

let x = ();
let y = ();
let z = Generic(&x, &y);
use spidermeme::SameTypeAs;

struct Generic<'a, 'b>(&'a str, &'b str) where &'a str: SameTypeAs<&'b str>;

let x: &'static str = "x";
let y = String::from("y");
let z = Generic(x, &y);

Function pointers should work:

use spidermeme::SameTypeAs;
use static_assertions::{assert_impl_all, assert_not_impl_any};

assert_impl_all!(fn(i32) -> i32: SameTypeAs<fn(i32) -> i32>);
assert_not_impl_any!(fn(i32) -> i32: SameTypeAs<fn(i32) -> i64>);

Closures should also work:

use spidermeme::SameTypeAs;

struct Pair<T1, T2>(T1, T2);

trait Heterogeneous {
    fn is_same(&self) -> bool;
}
impl<T1, T2> Heterogeneous for Pair<T1, T2> {
    fn is_same(&self) -> bool { false }
}
impl<T1, T2> Pair<T1, T2> where T1: SameTypeAs<T2> {
    fn is_same(&self) -> bool { true }
}

let x = || 1;
let y = || 1;
let same = Pair(x, x);
let different = Pair(x, y);

assert!(same.is_same());
assert!(!different.is_same());

Implementors

impl<T> SameTypeAs<T> for T[src]

Loading content...