Created
January 7, 2020 12:00
-
-
Save rust-play/9e1b47a89f17cdea261a424ae6965ca1 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![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