-
-
Save fujitayy/e56bf2df554495cf0067c6c74a086c46 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains 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
//! newtype patternで簡単に元の型と同等の機能を提供するには? | |
use itertools::Itertools; | |
macro_rules! impl_as { | |
($newtype:ty, $basetype:ty, $field:tt, $method:ident) => { | |
impl $newtype { | |
fn $method(&self) -> &$basetype { | |
&self.$field | |
} | |
} | |
impl AsRef<$basetype> for $newtype { | |
fn as_ref(&self) -> &$basetype { | |
self.$method() | |
} | |
} | |
} | |
} | |
macro_rules! impl_borrow { | |
($newtype:ty, $basetype:ty, $field:tt) => { | |
impl std::borrow::Borrow<$basetype> for $newtype { | |
fn borrow(&self) -> &$basetype { | |
&self.$field | |
} | |
} | |
} | |
} | |
macro_rules! impl_deref { | |
($newtype:ty, $basetype:ty, $field:tt) => { | |
impl std::ops::Deref for $newtype { | |
type Target = $basetype; | |
fn deref(&self) -> &$basetype { | |
&self.$field | |
} | |
} | |
} | |
} | |
#[derive(Debug, Clone)] | |
struct CsvLine(String); | |
impl_as!(CsvLine, str, 0, as_str); | |
impl_as!(CsvLine, std::string::String, 0, as_string); | |
impl_borrow!(CsvLine, str, 0); | |
impl_borrow!(CsvLine, std::string::String, 0); | |
impl_deref!(CsvLine, str, 0); | |
impl CsvLine { | |
fn from_columns<'a, I, S>(columns: I) -> CsvLine | |
where | |
S: AsRef<str> + 'a, | |
I: Iterator<Item = &'a S> | |
{ | |
CsvLine(columns.map(|s| s.as_ref()).join(",")) | |
} | |
} | |
fn main() { | |
let columns = ["aaa", "bbb", "ccc"]; | |
let csv_line = CsvLine::from_columns(columns.iter()); | |
println!("{:?}", csv_line); | |
println!("{}", csv_line.as_str()); | |
println!("{}", csv_line.as_string()); | |
csv_line.as_str().split(",").enumerate().for_each(|(i,c)| println!("{}: {}", i, c)); | |
let s: &str = &csv_line; | |
println!("{}", s); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment