What does `self` mean in `use`?

I added self that compiler told me.
But I'm confusing about it.

For example, I have a mod foo (src/foo/mod.rs):

mod bar;
use self::bar::aaaaa;

which bar is src/foo/bar.rs.
if I write use bar::aaaa; it will failed to compile.

So, why? and what is the proper way to solve it?

Thank you

Solution

Just do what compiler said

1 Like

by default, use is absolute, that is, it starts resolving the path from the crate root. use self:: makes it relative, instead resolving the path from the spot you're at.

sounds like your options are what you wrote, or use foo::bar::aaaaa;

5 Likes

I've seen cases like std::io::{self,Cursor}; which means explicitly use std::io::Cursor and also use std::io itself. Thus, Cursor need not be prefixed but you'd still need to do io::BufReader and so on.

3 Likes

Ever since using Rust, I've wished for this in Python.

In Python, since there's no self for imports, you have to do:

import std.io
from std.io import Cursor

Which now feels redundant. Rust ruins me for many languages.

Well if you can avoid using Python, I recommend JavaScript or Lua for embedding into Rust.

Using the absolute path foo::bar::aaaaa will break when you decide to move foo inside another module.

Consider this example with mods foo and bar, and a function in foo using a function in bar with an absolute path:

Here is what happens when we move foo inside a module. The function in foo is no longer able to use the function in bar because the absolute path broke:

1 Like