Crates.io | same-as |
lib.rs | same-as |
version | 1.0.0 |
source | src |
created_at | 2023-05-12 07:30:53.75809 |
updated_at | 2023-05-12 07:30:53.75809 |
description | Type equality in stable Rust. |
homepage | |
repository | https://github.com/wrsturgeon/same-as |
max_upload_size | |
id | 862747 |
size | 5,154 |
A toy example that demonstrates the basics:
use same_as::SameAs;
trait Eat<T> { fn eat<U: SameAs<T>>(_: U); } // Please don't actually write this
struct MrCreosote;
impl Eat<u8> for MrCreosote { fn eat<U: SameAs<u8>>(_: U) {} }
MrCreosote::eat(0_u8); // wafer-thin type
This won't compile:
// ...
struct MrCreosote;
impl Eat<u8> for MrCreosote { fn eat<U: SameAs<u8>>(_: U) {} }
MrCreosote::eat(0_u16); // kaboom
Sometimes you need it where Rust can't leverage it now, e.g. defining a Haskell-style monad in Rust:
pub trait Monad<A>: SameAs<Self::Constructor<A>> { // <-- Enforces that e.g. for `Maybe<A>`, `Self::Constructor` is effectively just the type constructor `Maybe`.
type Constructor<B>: Monad<B>; // In this `impl`, `Self` is really `Self<A>`, but we want to make `Self<B>` below.
fn bind<B, F: Fn(A) -> B>(self, f: F) -> Self::Constructor<B>;
}
So this would work:
pub enum Maybe<A> { Nothing, Just(A) }
impl<A> Monad<A> for Maybe<A> { type Constructor<B> = Maybe<B>; }
but we can prove that this won't, and so we can safely simulate type constructors in Rust:
pub enum Maybe<A> { Nothing, Just(A) } // deception! vvvvvv
impl<A> Monad<A> for Maybe<A> { type Constructor<B> = Option<B>; }