Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
737 views
in Technique[技术] by (71.8m points)

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

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

pub trait BorrowMut<Borrowed>: Borrow<Borrowed>
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:

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


1 especially see section 5.20 Traits
2 and section 6.1.9 Traits See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<T> BorrowMut<[T]> for Vec<T>

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...