我想在模块中导出一个函数,以便人们使用。但是,在大约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
或其他内容显式覆盖它)。我该怎么办?
答案 0 :(得分:3)
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
答案 1 :(得分:2)
您可以将函数标记为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