Skip to content

Instantly share code, notes, and snippets.

@jpastuszek
Forked from rust-play/playground.rs
Last active January 7, 2020 12:02
Show Gist options
  • Save jpastuszek/488a74f840c5b6979da7b39b332b6512 to your computer and use it in GitHub Desktop.
Save jpastuszek/488a74f840c5b6979da7b39b332b6512 to your computer and use it in GitHub Desktop.
Rust: Using const generics on trait to write CSV records of const number of columns
#![feature(const_generics)]
#![feature(const_generic_impls_guard)]
trait CsvRecord<const COLS: usize> {
fn columns() -> [&'static str; COLS];
fn values(&self) -> [String; COLS];
}
struct Foo {
id: u32,
bar: String,
}
impl CsvRecord<2> for Foo {
fn columns() -> [&'static str; 2] {
["id", "bar"]
}
fn values(&self) -> [String; 2] {
[self.id.to_string(), self.bar.clone()]
}
}
struct Bar {
id: u32,
bar: String,
baz: String,
}
impl CsvRecord<3> for Bar {
fn columns() -> [&'static str; 3] {
["id", "bar", "baz"]
}
fn values(&self) -> [String; 3] {
[self.id.to_string(), self.bar.clone(), self.baz.clone()]
}
}
fn write<R: CsvRecord<COLS>, const COLS: usize>(record: &R)
where
[&'static str; COLS]: std::array::LengthAtMost32,
[String; COLS]: std::array::LengthAtMost32
{
println!("{:?} {:?}", R::columns(), record.values());
}
fn main() {
let foo = Foo {
id: 21,
bar: "fds".into(),
};
write(&foo);
let bar = Bar {
id: 21,
bar: "fds".into(),
baz: "xdr".into(),
};
write(&bar);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment