Rust Programming: Relative Paths with super

0

Starting Relative Paths with super is a way to reference an item that we know is in the parent module. This can be useful when the module is closely related to the parent, but the parent might be moved elsewhere in the module tree someday. For example, the code snippet below shows how to use super to reference the deliver_order function, which is defined in the parent module.

fn deliver_order() {}


mod back_of_house {

    fn fix_incorrect_order() {

        cook_order();

        super::deliver_order();

    }


    fn cook_order() {}

}

The fix_incorrect_order function is in the back_of_house module, so we can use super to go to the parent module of back_of_house, which in this case is crate, the root. From there, we look for deliver_order and find it.

We think the back_of_house module and the deliver_order function are likely to stay in the same relationship to each other and get moved together should we decide to reorganize the crate's module tree. Therefore, we used super so we'll have fewer places to update code in the future if this code gets moved to a different module.

Post a Comment

0Comments
Post a Comment (0)