Writing generic function

How to write a declaration of function that can accept either stderr or stdout stream?

fn read_std_stream(
    stdout_or_stderr: ???,);

You are looking for a type implementing Write trait:

fn<T: Write> read_std_stream(
    stdout_or_stderr: &mut T)
2 Likes

Hi, thanks, it is actually std::io::Read but you nudged me in the right direction.
Thank you

Note there is also std::io::BufRead, which would require the caller to buffer the stream. In cases where buffered reading is required, I'm not sure whether it's more idiomatic to make a function accept types implementing std::io::Read and create their own std::io::BufReader where needed inside the function, or whether it's better to demand an argument to implement BufRead when the function requires buffering (I assume one would prefer using the BufRead trait, but maybe this also depends on the context / use case).

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.