rust - 如何在函数调用时显示编译器警告?

标签 rust compiler-warnings static-analysis

我有一个函数要导出到我的模块中,以便人们可以使用它。然而,在大约 95% 的情况下,使用它是一个坏主意。

/// Check whether foo is a metasyntactic variable.
/// 
/// **Using this function is a mistake.** This function is slow,
/// since checking widgets is an extremely expensive operation.
/// You should be keeping track of what's what, and ideally will
/// never need to use this function.
/// 
/// If you _do_ need to use this function, please consider a refactor.
pub fn test_widget(foo: String) -> bool {
    false
}

它主要用于文档和测试目的。但是,由于大约 5% 的情况下这种东西可能真正有用,所以我想保留它。

希望人们不小心使用它,所以我想让函数调用导致编译器警告(除非他们用 allow 或其他东西显式覆盖它)。我该怎么做?

最佳答案

您可以将函数标记为 deprecated :

// Consider summarizing this and linking to the docs, rather than putting the
// entire message here.
#[deprecated(note=
    "**Using this function is a mistake.**
This function is slow,
since checking widgets is an extremely expensive operation.
You should be keeping track of what's what, and ideally will
never need to use this function.

If you _do_ need to use this function, please consider a refactor.")]
pub fn test_widget(foo: String) -> bool {
    /// Check whether foo is a metasyntactic variable.
    false
}

如果用户使用该功能,他们会收到警告:

warning: use of deprecated item 'test_widget': **Using this function is a mistake.**
This function is slow,
since checking widgets is an extremely expensive operation.
You should be keeping track of what's what, and ideally will
never need to use this function.

If you _do_ need to use this function, please consider a refactor.

但他们可以使用 #[allow(deprecated)] 将其关闭:

#[allow(deprecated)]
test_widget("Hello, World!".to_string()); // no warning

Playground link.

关于rust - 如何在函数调用时显示编译器警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56741004/

相关文章:

c++ - 在 Qt Creator 中禁用 "The build directory needs to be at the same level as the source directory"警告

c - 在 GCC 中禁用 "did you mean..."建议

java - 用于提取方法/注释的 Java 源代码静态代码解析器

c# - 有没有什么工具可以分析c#程序中变量之间的依赖关系?

rust - 如何使用任意键类型序列化和反序列化 BTreeMaps?

pointers - 为什么在对取消引用的枚举进行匹配时必须使用 ref?

reactjs - workerize-loader 编译后无法工作( react typescript )

c# - 如何摆脱 Visual Studio 中的 "[some event] never used"编译器警告?

rust - 为什么使用 Rust 将可变结构传递给函数会导致不可变字段?

configuration-files - Cppcheck GUI : Excluding a file or folder from checking