Skip to content

Instantly share code, notes, and snippets.

@sagebind
Created December 19, 2019 05:27
Show Gist options
  • Save sagebind/18a32a779988f9770327b702ddba9c12 to your computer and use it in GitHub Desktop.
Save sagebind/18a32a779988f9770327b702ddba9c12 to your computer and use it in GitHub Desktop.
#![feature(specialization)]
const fn type_eq<T: ?Sized, U: ?Sized>() -> bool {
trait Bool {
const VALUE: bool;
}
struct True;
impl Bool for True {
const VALUE: bool = true;
}
struct False;
impl Bool for False {
const VALUE: bool = false;
}
trait TypeEq<T: ?Sized> {
type Equals: Bool;
}
impl<T: ?Sized> TypeEq<T> for T {
type Equals = True;
}
impl<T: ?Sized, U: ?Sized> TypeEq<T> for U {
default type Equals = False;
}
<T as TypeEq<U>>::Equals::VALUE
}
fn main() {
assert!(!type_eq::<String, str>());
assert!(!type_eq::<&'static str, str>());
assert!(type_eq::<String, String>());
}
@sagebind
Copy link
Author

Implement a function const fn type_eq<T: ?Sized, U: ?Sized>() -> bool that returns true or false at compile time whether two generic type parameters are the same or not. Requires specialization on nightly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment