Created
February 9, 2018 22:14
-
-
Save mickvangelderen/cefee8b0cf1f003abc34739f05c573c3 to your computer and use it in GitHub Desktop.
How to create and use constants 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
trait Pi { | |
fn give_me_pi() -> f32; | |
} | |
struct PI(); | |
impl Pi for PI { | |
fn give_me_pi() -> f32 { | |
3.14 | |
} | |
} | |
fn circumference<T: Pi>(radius: f32, _pi: T) -> f32 { | |
2.0 * T::give_me_pi() * radius | |
} | |
fn main() { | |
// A constant should not take any space. | |
assert_eq!(0, std::mem::size_of::<PI>()); | |
let radius = 10.0; | |
// prints radius: 10, circumference: 62.800003 | |
println!("radius: {}, circumference: {}", radius, circumference(radius, PI())); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment