Created
July 26, 2023 15:48
-
-
Save Ionizing/96495186fb95bc9bd5bb04cfa040d4f1 to your computer and use it in GitHub Desktop.
Function overloading 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
// Credits to (Telegram): | |
// - @QC_Grove (zh) | blog.quarticcat.com (en/zh) | |
// - @bdbai_chat | |
trait Foo<T, U> { | |
type Output; | |
fn foo(a: T, b: U) -> Self::Output; | |
} | |
impl Foo<i32, f64> for () { | |
type Output = f64; | |
fn foo(a: i32, b: f64) -> Self::Output { | |
a as f64 + b | |
} | |
} | |
impl Foo<i32, i32> for () { | |
type Output = f64; | |
fn foo(a: i32, b: i32) -> Self::Output { | |
(a + b) as f64 | |
} | |
} | |
fn foo<T, U>(a: T, b: U) -> <() as Foo<T, U>>::Output | |
where (): Foo<T, U> { | |
<()>::foo(a, b) | |
} | |
fn main() { | |
println!("{}", foo(114, 514.0)); | |
println!("{}", foo(114, 514)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment