> let x: i32 = 16i32;
Otherwise, it's a very comprehensive article. The only missing parts are the async/await keywords and the sync primitives (like Mutexes/RwLocks).
> let x: i32 = 16i32;
Otherwise, it's a very comprehensive article. The only missing parts are the async/await keywords and the sync primitives (like Mutexes/RwLocks).
I find the rust syntax a little difficult to read. Take "16i32" for example - it's not immediately clear which part is the actual value.
I agree that something like 16i32 is difficult to read which is why I typically use an underscore to separate the number from the type if I need to write a literal that way (e.g. sometimes I find 0_f64 easier to grok than 0.0).
I didn't know you could use an underscore to separate the type - I think that definitely helps!
0xFFFF_FFFF // easier to count than 8 Fs
And you can use that with type suffixes: let a = 255_u8;
Although in that case, you'd probably either omit u8 entirely, letting the compiler infer the type of 'a' from usage, or use a colon to give it ane explicit type.Type suffixes are especially useful for arguments to generic functions:
write_le(12_u32);
write_le(255_u8);As a rust noob, I didn't realise rust supported the same syntax, or that you could use it to separate the type from the value (which in rust's case, I find really helps readability).
> my_function( 44i32 );
That makes it clear from the code that function accepts an i32 and not any number.
You can also use generics to allow you to accept a wider variety of numbers, e.g.:
fn takes_a_float_like_number<T>(number: T) where T: Into<f64> {
// Number will now be a 64-bit IEEE floating point object
// for this scope
let number = number.into();
}
This will only compile if your type is small enough to fit into an f64. So takes_a_float_like_number(500_u32) will compile but takes_a_float_like_number(500_i64) will not. The error message will be a wee bit obtuse as it will be something like "trait Into<f64> not implemented for i64".In other languages I've seen something like "type {} can't represent literal of value {}" which is a bit more generic and applies to things like floats/signed ints and values that are too small/negative.
let x = 65536_i32;
Or let x: i32 = 65_536;