Use/import confusion

Hello fellow Rustaceans. I have a rather simple question on how the use imports are working.

I noticed that I cannot use file.read_to_string() unless I use std::io::read where file is returned from File::open().

So basically, I would expect that read_to_string() is part of File but it is actually part of io, but it is called from a File object.

My only area of confusion is how a function from one mod can be used on an object from another mod and/or how I could tell in the future because this page has it under std::fs but I was getting compiler errors saying it could not be found until I finally tried std::io. Thanks.

You’re running into two different things:

The second is part of the Read trait, which File implements. The first one is a free-standing function.

In order to be able to call methods that a trait defines, the trait must be in scope. That’s why you need the use for it. The function, on the other hand, doesn’t come from a trait: it’s just a function.

Does that help at all?

1 Like

Yes that cleared up the ambiguity, thank you!

1 Like