generics - 问号在类型参数绑定(bind)中意味着什么?

标签 generics rust

我找到了 std::borrow::BorrowMut 的定义:

pub trait BorrowMut<Borrowed>: Borrow<Borrowed>
where
    Borrowed: ?Sized,
{
    fn borrow_mut(&mut self) -> &mut Borrowed;
}

Sized 前面的问号在这个类型参数绑定(bind)(借用:?Sized)中是什么意思?

我咨询过:

但没有找到解释。请在您的回答中提供引用。


¹ 特别参见5.20 Traits部分
² 6.1.9 Traits部分

最佳答案

这意味着特征是可选的。当前语法在 DST syntax RFC 中引入.

据我所知,唯一适用于 ? 的特征是 Sized

在这个具体的例子中,我们可以为未调整大小的类型实现BorrowMut,比如[T]——注意没有& 这里!

一个内置实现利用了它:

impl<T> BorrowMut<[T]> for Vec<T>

作为Matthieu M. adds :

This is a case of a widening bound; in general bounds impose more constraints, but in the case of Sized it was decided that unless otherwise noted a generic T would be assumed to be Sized. The way to note the opposite would be to mark it ?Sized ("maybe Sized").

关于generics - 问号在类型参数绑定(bind)中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30333607/

相关文章:

java - 互补的泛型类

java - 如何在 Java 中使用泛型创建静态 'Object Holder' 类

java - 参数化类型参数?

rust - 在 Rust 中使用 UUID

swift - 协议(protocol)不符合自身?

java - 如何限制泛型类型不扩展类?

rust - Rust 中的浅复制和移动

rust - 类型转换和转换

RuSTLs(或 briansmith/ring)AES CBC 选项 DONT_INSERT_EMPTY_FRAGMENTS 模拟

multithreading - 同时将相同的可变函数应用于同一Vec的不同元素