Как я могу отобразить предупреждение компилятора при вызове функции? - PullRequest
3 голосов
/ 24 июня 2019

В моем модуле есть функция, которую я хочу экспортировать, чтобы люди могли ее использовать. Однако в ≈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 или чего-то еще ). Как я могу это сделать?

Ответы [ 2 ]

3 голосов
/ 27 июня 2019

Кажется, что 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
2 голосов
/ 24 июня 2019

Вы можете пометить функцию как устарела :

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

Ссылка на игровую площадку.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...