gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:57:57 26 4
gpt4 key购买 nike

我有一个函数要导出到我的模块中,以便人们可以使用它。然而,在大约 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com