Created
December 18, 2015 15:53
-
-
Save ayosec/9efb44648d0d9c046826 to your computer and use it in GitHub Desktop.
Rust: Closure in a struct
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
trait Separator { | |
fn is_sep(&self, c: char) -> bool; | |
} | |
struct ClosureSeparator<F: Fn(char) -> bool>(F); | |
impl<F> Separator for ClosureSeparator<F> where F: Fn(char) -> bool { | |
#[inline] | |
fn is_sep(&self, c: char) -> bool { | |
self.0(c) | |
} | |
} | |
trait AsSeparator { | |
type Inner: Separator; | |
fn as_separator(self) -> Self::Inner; | |
} | |
impl<F> AsSeparator for F where F: Fn(char) -> bool + 'static { | |
type Inner = ClosureSeparator<F>; | |
#[inline] | |
fn as_separator(self) -> ClosureSeparator<F> { | |
ClosureSeparator(self) | |
} | |
} | |
fn seps<S: AsSeparator>(build: S) { | |
let s = build.as_separator(); | |
println!("is_sep(' ') = {}", s.is_sep(' ')); | |
println!("is_sep('a') = {}", s.is_sep('a')); | |
} | |
fn main() { | |
seps(|c: char| c.is_whitespace()); | |
seps(|c: char| c.is_alphanumeric()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment