Skip to content

Instantly share code, notes, and snippets.

@zohnannor
Created October 23, 2022 21:02
Show Gist options
  • Save zohnannor/f39e413e0dcacfdb1a2cb5ec5bc9fcd6 to your computer and use it in GitHub Desktop.
Save zohnannor/f39e413e0dcacfdb1a2cb5ec5bc9fcd6 to your computer and use it in GitHub Desktop.
`adt_const_params` fun
#![feature(adt_const_params)]
#![allow(incomplete_features, clippy::disallowed_names)]
#[derive(Debug)]
struct Foo {
bar: i32,
baz: String,
}
trait Field<T, const NAME: &'static str> {}
trait Get<T> {
fn get<const NAME: &'static str>(&self) -> &T
where
Self: Field<T, NAME>;
}
impl Field<i32, "bar"> for Foo {}
impl Get<i32> for Foo {
fn get<const NAME: &'static str>(&self) -> &i32 {
&self.bar
}
}
impl Field<String, "baz"> for Foo {}
impl Get<String> for Foo {
fn get<const NAME: &'static str>(&self) -> &String {
&self.baz
}
}
fn main() {
let foo = Foo {
bar: 42,
baz: "666".into(),
};
dbg!(foo.get::<"bar">());
dbg!(foo.get::<"baz">());
// dbg!(foo.get::<"quux">()); -- the trait `Field<_, "quux">` is not implemented for `Foo`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment