Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't `use std::io` enough here?

Tags:

rust

I tried to compile the following program:

use std::io;

fn main() {
    io::stdout().write(b"Please enter your name: ");
    io::stdout().flush();
}

Unfortunately, compiler resisted:

error: no method named `write` found for type `std::io::Stdout` in the current scope
 --> hello.rs:4:18
  |
4 |     io::stdout().write(b"Please enter your name: ");
  |                  ^^^^^
  |
  = help: items from traits can only be used if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
  = help: candidate #1: `use std::io::Write`

I found that I needed to do use std::io::{self, Write};. What does use std::io; actually do then and how do (if possible) I pull all names defined in std::io? Also, would it be a bad style?

like image 213
d33tah Avatar asked Dec 18 '22 11:12

d33tah


1 Answers

What does use std::io; actually do then?

It does what every use-statement does: makes the last part of the used path directly available (pulling it into the current namespace). That means that you can write io and the compiler knows that you mean std::io.

How do I pull all names defined in std::io?

With use std::io::*;. This is commonly referred to as glob-import.

Also, would it be a bad style?

Yes, it would. Usually you should avoid glob-imports. They can be handy for certain situations, but cause a lot of trouble on most cases. For example, there is also the trait std::fmt::Write... so importing everything from fmt and io would possibly result in name-clashes. Rust values explicitness over implicitness, so rather avoid glob-imports.

However, there is one type of module that is usually used with a glob-import: preludes. And in fact, there is even a std::io::prelude which reexports important symbols. See the documentation for more information.

like image 141
Lukas Kalbertodt Avatar answered Jan 04 '23 22:01

Lukas Kalbertodt