What does `self` mean in `use`?


#1

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


#2

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;


#3

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.


#4

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.


#5

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


#6

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:
https://play.rust-lang.org/?gist=979e91b3c74abd5c5ca493e8b0ad00c2&version=stable

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:
https://play.rust-lang.org/?gist=831523558784225a98c1e704732cdefa&version=stable