I have seen the following possibilities:
let first_float: f64 = 3.4;
let second_float = 4.5f64;
let third_float = 5.6 as f64;
Are there any other ways to declare a float? I don't mean the different floating-point types like f32 and f64.
Sure there are.
First let's explain what your ways do. They combine different features of the language, and while they all seem to "declare a float in Rust", they are not simple declarations.
// Float literals will become either `f32` or `f64`
// depending on how they're are used:
let first_float: f64 = 3.4;
// This one is really a `f64` literal,
// typically only used when inference isn't enough
let second_float = 4.5f64;
// This is an identity cast, the untyped literal will give f64 since that
// is what is needed at the end. I would never use this.
let third_float = 5.6 as f64;
Floats are f64 default, so this is what you should use most of the time:
let _another_one = 3.4;
And here are a few other over-complicated ways:
let _another_one = 17./5.; // good old math
let _another_one: f64 = From::from(3.4); // From::from identity conversion
let _another_one = f64::from(3.4); // Same as above, no inference
let _another_one = "3.4".parse::<f64>().unwrap(); // Why not parse them?
let _another_one = f64::from_bits(4614838538166547251); // When you really need your bits right
let _another_one = unsafe { std::mem::transmute::<_, f64>(4614838538166547251u64) }; // same as above, but only if you want to be naughty
let (_another_one,): (f64,) = (3.4,); // Deconstructing a one-tuple.
// Deserialize from JSON:
let _another_one: f64 = {
use serde; // 1.0.104
use serde_json; // 1.0.44
serde_json::from_str("3.4").unwrap()
};
// This requires #![feature(type_ascription)] at the moment:
let _another_one = 3.4 : f64;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With