rust ...为什么要将函数从 rs 文件导入到库中? - 未能解决 : use of undeclared type or module `client`

标签 rust

-src/
-lib.rs
-client.rs

哇,我对 rust 和他们的文档感到困惑。为什么使用rust 你不使用下面的?

client.rs 

pub fn connect(x: usize) -> usize {
   return x
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_connect() {
        assert_eq!(connect(5), 5);
    }
}

cannot find function `connect` in this scope

库文件
mod client;

pub fn fu() -> usize {
    let really = client::connect(5);
    return really
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }

    #[test]
    fn test_fu() {
        assert_eq!(fu(),5);
    }

}

cannot find function `fu` in this scope




cargo test

error[E0425]: cannot find function `connect` in this scope
  --> src/client.rs:12:20
   |
12 |         assert_eq!(connect(5), 5);
   |                    ^^^^^^^ not found in this scope
   |
help: consider importing this function
   |
11 |     use crate::client::connect;
   |

error[E0425]: cannot find function `fu` in this scope
  --> src/lib.rs:17:20
   |
17 |         assert_eq!(fu(),5);
   |                    ^^ not found in this scope
   |
help: consider importing this function
   |
11 |     use crate::fu;
   |

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0425`.

最佳答案

您正在使用 test用于测试的模块。您需要将外部模块带入范围。您可以使用 super像这样关联它:

mod client;

pub fn fu() -> usize {
    let really = client::connect(5);
    return really
}

#[cfg(test)]
mod tests {
    use super::*; // bring to scope every declared item from the outer (lib) module

    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }

    #[test]
    fn test_fu() {
        assert_eq!(fu(),5);
    }

}

关于rust ...为什么要将函数从 rs 文件导入到库中? - 未能解决 : use of undeclared type or module `client` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61793249/

相关文章:

rust - 在 Rust 中使用 unwrap_or_else 进行错误处理

rust - 如何指定工作区成员只能在特定平台上构建?

string - 如何在 Rust 中惯用且高效地解析由字母和数字组成的字符串?

Rust 零复制生命周期处理

function - 没有参数的 Rust 函数和有一个未使用参数的函数有什么区别?

rust - 我可以编写一个使自己变异然后生成对自身的引用的Iterator吗?

rust - 我如何向编译器解释通用函数返回可用于减法的数据?

rust - 为什么不能在同一结构中存储值和对该值的引用?

windows - Rust 程序需要 libusb DLL 存在,即使它是静态链接的

rust - 如何链接到 rustdoc 中的其他 fns/structs/enums/traits?