Last active
August 22, 2021 01:42
-
-
Save nakagami/d6beaf223bbee2e4d6780d7438917dd4 to your computer and use it in GitHub Desktop.
dynamic return type in Rust
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
// dynamic return type in Rust | |
#[derive(Clone)] | |
struct V { | |
i:i32, | |
s:String, | |
} | |
trait ToVal<T> { | |
fn to_val(self) -> T; | |
} | |
impl ToVal<i32> for V { | |
fn to_val(self) -> i32 { | |
self.i | |
} | |
} | |
impl ToVal<String> for V { | |
fn to_val(self) -> String { | |
self.s.clone() | |
} | |
} | |
fn main() { | |
let v = V{i:123, s:String::from("test string")}; | |
let i:i32 = v.clone().to_val(); | |
let s:String = v.clone().to_val(); | |
println!("{}, {}", i, s); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment