Why isn't there a `std::fs::read<T>()` function?

Currently in Rust's std there are 2 functions that read directly the content of a file:

fn read<P: AsRef<Path>>(path: P) -> Result<Vec<u8>>

and

fn read_to_string<P: AsRef<Path>>(path: P) -> Result<String>

the question that I ask myself is, why isn't there a trait (e.g. FromRead / Readable, ...) that could allow to do this:

fn read<P: AsRef<Path>, T: FromRead>(path: P) -> Result<T>

Was that ever thought when designing std::fs ? If so, what are the arguments against it ?

This was probably discussed early on in the development of the standard library, but I'm not sure. The standard library offers a very high level of stability and is small by design, unlike standard libraries of many other common programming languages. The threshold for a feature to make it into std is very high, given that it has to be maintained practically forever (or at least until we get a Rust 2.0). That's why, for example, there is no asynchronous runtime, no http primitives and basically no serialization support implemented in the standard library. Instead, these are provided by the greater ecosystem by crates like tokio, http or serde (which you'd probably want to look into if you want to read a T: Deserialize from somewhere). Anyway, you might want to consider posting your question on the internals forum, which is better suited for such questions about Rust and its design and where you might get a more detailed answer.

1 Like

thanks i'll post this to the internal forum!

Would something like Vec<u64> implement FromRead? If so could you copy data from a big-endian to a little-endian machine and have both of them deserialize identically?

1 Like

To expand on @jofas 's answer, the standard library doesn't want to add anything where there is not a single, obvious design. Occasionally the value is so high that they have broken that desire, but that is often the source of some of the worst parts of the standard library.

Serialization is an extremely diverse and complex topic, not only in what formats are supported, but the interface used to describe what structure is expected, streaming support, self describing vs implicit structure, trade-offs in code size vs execution speed, and so on. serde is extremely popular for a reason, it's close enough to perfect for it's specific design, but that design does have some pretty serious inherent downsides (mostly in that it massively bloats code size and therefore build time)

3 Likes