在功能调用时,如何显示编译器警告



我想在模块中导出一个函数,以便人们可以使用它。但是,在约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%的情况可能确实有用,所以我想保持它。

i 不希望人们意外使用它,因此我想对功能进行调用引起编译器警告(除非他们用allow明确覆盖它或其他内容(。我该怎么做?

您可以将功能标记为已弃用:

// 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

游乐场链接。

must_use似乎在这里很合适,并允许指定自定义消息:

#[must_use = "Calling this function is a bad idea"]
pub struct BadIdeaFunction(bool);
impl BadIdeaFunction {
    pub fn i_acknowledge_calling_this_function_is_a_bad_idea(self) -> bool {
        self.0
    }
}
/// 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() -> BadIdeaFunction {
    BadIdeaFunction(false)
}
fn main() {
    test_widget(); // gives a warning, but the next one doesn't
    test_widget().i_acknowledge_calling_this_function_is_a_bad_idea();
}

这会通过自定义消息创建警告:

warning: unused `BadIdeaFunction` that must be used
  --> src/main.rs:23:5
   |
23 |     test_widget();
   |     ^^^^^^^^^^^^^^
   |
   = note: #[warn(unused_must_use)] on by default
   = note: Calling this function is a bad idea

最新更新