是否可以在泛型函数中排除引用参数?

Is it possible to exclude reference arguments in a generic function?

由于通用类型参数 T 可以是任何类型,包括引用,我想知道是否可以在通用函数中选择退出引用,即能够编写如下内容:

use std::ops::Deref;

fn foo<T: !Deref>(x: T) -> T {}

然而,这是不允许的,并且在解析阶段已经中断。

我读到 optin_builtin_traits,但它只支持选择退出自动特征,所以它也不起作用,因为 Deref 不是自动特征。

有可能实现吗?

是的,您可以为此使用自动特征:

#![feature(auto_traits)]
#![feature(negative_impls)]

auto trait NotReference {}

impl<'a, T> !NotReference for &'a T {}
impl<'a, T> !NotReference for &'a mut T {}

fn no_references<T: NotReference>(_: T) {}

fn main() {
    no_references(42); // OK
    no_references(&42); // the trait bound `&{integer}: NotReference` is not satisfied
    no_references("hello"); // the trait bound `&str: NotReference` is not satisfied

    no_references(vec![1, 2, 3]); // OK

    let x = vec![1, 2, 3];
    no_references(x.iter()); // the trait bound `&{integer}: NotReference` is not satisfied in `std::slice::Iter<'_, {integer}>`
}

请注意,这也排除了:

  • 具有 'static 生命周期的引用,如“hello”调用所示
  • 包含引用的任何结构,如iter()调用
  • 所示

I could possibly exclude some lifetime issues.

实际上,这就是 'static 绑定的作用:

fn foo<T: 'static>(x: T) -> T {}