HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustMajor

What does the question mark mean in a type parameter bound?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
boundmarktheparametertypedoesmeanwhatquestion

Problem

I found the definition for std::borrow::BorrowMut:

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


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

I consulted:

  • 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.

¹ especially see section 5.20 Traits

² and section 6.1.9 Traits

Solution

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

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

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 BorrowMut for Vec


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

Code Snippets

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

Context

Stack Overflow Q#30333607, score: 82

Revisions (0)

No revisions yet.