by Sag0Sag0 · 9y ago · 0 comments
Things like converting a String to an i64 are a pain. There is large amount of boilerplate code needed.
All in all this is a personal preference. I prefer some unsafeness in c to (in my opinion) the constant inconvenience of programming in rust.
If you mean reading the bytes of the string as an i64, that's
unsafe { *(s.as_ptr() as *const i64) }
...which is a bit more verbose than C's *(int64_t *) ptr
but not that verbose, especially given that there will often be more code in the unsafe block. On the other hand, in C that's often technically undefined behavior due to strict aliasing, so to get strictly conformant code you have to use memcpy. Rust has no strict aliasing.(I wouldn't actually recommend the above Rust code, because it doesn't verify that the string's length matches i64 - but neither does C, so it's a fair comparison. More idiomatic wrappers can be found in third-party crates like byteorder or pod.)
If you mean casting the pointer to the bytes to an i64, that's
s.as_ptr() as i64
which doesn't seem verbose. (No unsafe needed in that case.) let i = NativeEndian::read_i64(...);
Or if you're literally parsing a string of digits: let i: Option<i64> = digits.parse();
The `parse` method on strings is a particularly smooth piece of trait system magic.> Rust has no strict aliasing. does that mean that rust cannot optimize for things C could ? (real quesiton I don't know rust)