J'ai vu les possibilités suivantes :
let first_float: f64 = 3.4;
let second_float = 4.5f64;
let third_float = 5.6 as f64;
Existe-t-il d'autres moyens de déclarer un float ? Je ne parle pas des différents types à virgule flottante comme f32
et f64
.
Bien sûr qu'il y en a.
Expliquons d'abord ce que font vos méthodes. Ils combinent différentes fonctionnalités du langage, et bien qu'ils semblent tous "déclarer un float dans Rust", ce ne sont pas de simples déclarations.
// 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;
Les flottants sont f64
par défaut, c'est donc ce que vous devriez utiliser la plupart du temps :
let _another_one = 3.4;
Et voici quelques autres moyens trop compliqués :
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;
Cet article est collecté sur Internet, veuillez indiquer la source lors de la réimpression.
En cas d'infraction, veuillez [email protected] Supprimer.
laisse moi dire quelques mots