How to call functions that aren't inside a module from the test module?

前端 未结 1 1380
暖寄归人
暖寄归人 2021-01-14 02:09

These are the contents of my src/lib.rs file:

pub fn foo() {}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        foo();
    }
}
<         


        
相关标签:
1条回答
  • 2021-01-14 02:30

    You could use super:: to refer to the parent module:

    fn it_works() {
        super::foo();
    }
    

    In Rust 2015, you can use :: to refer to the root module of the crate:

    fn it_works() {
        ::foo();
    }
    

    In Rust 2018, you can use crate:: to refer to the root module of the crate:

    fn it_works() {
        crate::foo();
    }
    

    Or, as foo may be used repeatedly, you could use it in the module:

    mod tests {
        use foo;         // <-- import the `foo` from the root module
        // or
        use super::foo;  // <-- import the `foo` from the parent module
    
        fn it_works() {
            foo();
        }
    }
    

    For test modules, it's also common to import everything from the parent module:

    mod tests {
        use super::*;  // <-- import everything from the parent module
    
        fn it_works() {
            foo();
        }
    }
    
    0 讨论(0)
提交回复
热议问题