Skip to content

Instantly share code, notes, and snippets.

@mickvangelderen
Created February 9, 2018 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mickvangelderen/cefee8b0cf1f003abc34739f05c573c3 to your computer and use it in GitHub Desktop.
Save mickvangelderen/cefee8b0cf1f003abc34739f05c573c3 to your computer and use it in GitHub Desktop.
How to create and use constants in Rust.
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