I just figured out how do have (generics const limited) dependable types in Rust

94 points vasilakisfil

I was trying to find out whether you can have generic const restrictions in the where clause, in the form like

use std::net::Ipv4Addr;

pub struct PrefixLen<const LEN: u8>;

pub struct IpV4Net {
    ip_addr: Ipv4Addr,
    prefix: u8,
}

impl<const LEN: u8> From<(Ipv4Addr, PrefixLen<LEN>)> for IpV4Net
where
    LEN <=32,
{
    fn from((ip_addr, len): (Ipv4Addr, PrefixLen<LEN>)) -> Self {
        Self {
            ip_addr,
            prefix: PrefixLen::LEN,
        }
    }
}

but seems like it's not possible :( HOWEVER, during my search, I somehow ended up in this comment, and hey it IS possible, using some more constructs (and on nightly):

#![feature(adt_const_params)]
#![feature(generic_const_exprs)]

use std::net::Ipv4Addr;

pub struct PrefixLen<const LEN: u8>;

pub struct IpV4Net {
    ip_addr: Ipv4Addr,
    prefix: u8,
}

enum Assert<const COND: bool> {}

trait IsTrue {}

impl IsTrue for Assert<true> {}

impl<const LEN: u8> From<(Ipv4Addr, PrefixLen<LEN>)> for IpV4Net
where
    Assert<{ LEN <= 32 }>: IsTrue,
{
    fn from((ip_addr, len): (Ipv4Addr, PrefixLen<LEN>)) -> Self {
        Self {
            ip_addr,
            prefix: PrefixLen::LEN,
        }
    }
}

rust playground link

Isn't that amazing ?! I suspect in ~2 years we will even have it on stable.

edit: Can someone fix the post's title do -> to 😂