Why `std` does not contain functionality for reading primitive types?
Hello everyone,
I have been trying to learn Rust for a couple of months now and I am finally coming to understand more and more of the language (still think it's great). However, one thing that I just fail to understand is why the Rust std does not contain functionality for reading primitive types. Of course, we have the Read trait which enables us to read bytes (much like Java's InputStream but then only for reading bytes). But why is there no functionality to read u32 or i64 from Read? I know that we have the byteorder crate which extends the Read trait to do such operations, however, reading primitive types feels like such a basic operation that one would suspect such functionality to be contained inside std. But maybe this assumption of mine just does not hold :)
I hope someone can clarify this for me :)
Posted Apr 9, 2019, 12:32 PM UTC
A big issue for
read_u64orread::<u64>is that there are four ways to interpret them, which are all wanted at some point:u64u64u64u64from textual representationSo the deliberately minimal and attempted unopinionated standard library doesn't offer this functionality, because then it'd have to bless one of the four options. People coming from higher level languages will probably expect the fourth, from lower level languages the third (but also often treat the third as the second).
Because Cargo makes pulling in library crates so easy, a sparse standard library doesn't matter as much. You can have properly versioned libraries to handle these situations which require these kinds of issues.
In cases when you want to parse text rather than interpret bytes, you're almost always better off reading and splitting strings first, as that makes the intent and effect a lot clearer than, say, Java's
Scannerwhere if you scan for numbers you have no control over how whitespace is/isn't present.In cases when you want to interpret bytes, the endianness really matters, because even if "all practical systems are littleendian in practice", many protocols aren't. You have to be explicit about what you want if you want consistent behavior. That's what the
byteordercrate offers.Not to forget middle-endian, which isn't used widely, but required for completeness sake.
Thanks for your answer! Makes it clear to me :)