问号在类型参数绑定中是什么意思? [英] What does the question mark mean in a type parameter bound?

查看:42
本文介绍了问号在类型参数绑定中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

What does the question mark in front of Sized mean in this type parameter bound (Borrowed: ?Sized)?

我咨询过:

  • The Rust Programming Language¹ book,
  • The Rust Reference², and also
  • What does "Sized is not implemented" mean? on Stack Overflow

但没有找到解释.请在您的回答中提供参考.

but didn't find an explanation. Please give a reference in your answer.


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

推荐答案

这意味着 trait 是可选的.当前语法在 DST 语法 RFC.

It means that the trait is optional. The current syntax was introduced in the DST syntax RFC.

我所知道的唯一适用于 ? 的特性是 Sized.

The only trait I am aware of that works for ? is Sized.

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

In this specific example, we can implement BorrowMut for unsized types, like [T] — note that there's no & here!

一个内置实现利用了这一点:

One built-in implementation makes use of that:

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

As Matthieu M. 补充:

这是一个扩大边界;一般来说,边界会施加更多约束,但在Sized的情况下,除非另有说明,否则将假定通用T为<代码>大小.注意相反的方法是将其标记为 ?Sized(也许 Sized").

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").

这篇关于问号在类型参数绑定中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆