When should `super` and `self` be used in mod imports?

I refactored some code that was a bunch of flat modules into a more nested structure that better modeled the data model hierarchy.

In Python, I often use relative imports to make packages modular and stand alone, so I thought I try the same thing in Rust.

In one module I ended up with these lines:

use super::super::color;
use super::{Drawable, Updateable, Vector};

When I started typing use super::super::color my first instinct was to consider the absolute path (in this case the alternative would be use game::color) because it looked pretty terse.

It seems like relative imports should generally be preferred to allow things to be more easily be refactored, but are there times I should lean towards absolute?

I think part of my initial shock is that in Python this would simply be:

import ..color

So Rust makes it a lot more obvious you are moving up in the chain. Something I'll probably just need to get used and in the end appreciate like most of the new things I've used in Rust.

Full code for context can be viewed here: https://github.com/johnthagen/rust-belt/pull/47

1 Like

I personally only use super in test modules to import things to test. I never use self.


Been wondering how to do this. I found a solution for those who get directed here with a similar question.

If you wanted to refer to the topmost directory in the project, you can use crate keyword. You could instead say

use crate::color;

if the module is close to the parent directory, that is.

1 Like