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

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

本文介绍了是否可以在泛型函数中排除引用参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Since the generic type parameter T can be of any type, including a reference, I was wondering if it was possible to opt out of references in generic functions, i.e. to be able to write something like:

use std::ops::Deref;

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

但是,这是不允许的,并且已经在解析阶段中断了.

This, however, is not allowed and breaks already at the parsing stage.

我了解了 optin_builtin_traits ,但是它仅支持选择不使用自动特征,因此也不起作用,因为 Deref 不是自动特征.

I read about optin_builtin_traits, but it only supports opting out of auto traits, so it wouldn't work either, because Deref is not an auto trait.

有可能实现这一目标吗?

Is it possible to achieve this?

推荐答案

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

Yes, you can use auto traits for this:

#![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}>`
}

请注意,这还排除了以下情况:

Note that this also precludes:

    如所示,具有'static 生存期的
  • 引用.致电
  • 包含引用的任何结构,如 iter()调用
  • 所示
  • references with the 'static lifetime, as shown by the "hello" call
  • any struct which contains a reference as well, as shown by the iter() call

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

Practically, that's what the 'static bound does:

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

这篇关于是否可以在泛型函数中排除引用参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 09:23