Skip to content

RangeXxx<&T> should implement RangeBounds<T> even if T is unsized #107196

@SOF3

Description

@SOF3

I tried this code:

use std::collections::BTreeMap;
pub fn foo(map: &BTreeMap<String, i32>) -> impl Iterator<Item = (&String, &i32)> {
    map.range::<str, _>("".."")
}

I expected to see this happen: This should compile since BTreeMap::range is supposed to accept a RangeBounds with an unsized type parameter

Instead, this happened: It does not compile with the error:

error[[E0277]](https://doc.rust-lang.org/stable/error-index.html#E0277): the size for values of type `str` cannot be known at compilation time
 --> src/lib.rs:3:25
  |
3 |     map.range::<str, _>("".."")
  |         -----           ^^^^^^ doesn't have a size known at compile-time
  |         |
  |         required by a bound introduced by this call
  |
  = help: the trait `Sized` is not implemented for `str`
  = help: the following other types implement trait `RangeBounds<T>`:
            std::ops::Range<&T>
            std::ops::Range<T>
  = note: required for `std::ops::Range<&str>` to implement `RangeBounds<str>`
note: required by a bound in `BTreeMap::<K, V, A>::range`

This is because Range<&str> does not implement RangeBounds<str>, because the current impl RangeBounds<str> for Range<&str> is as follows:

#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for Range<&T> {
    fn start_bound(&self) -> Bound<&T> {
        Included(self.start)
    }
    fn end_bound(&self) -> Bound<&T> {
        Excluded(self.end)
    }
}

Similarly, for other range structs except (Bound, Bound) and RangeFull (the latter of which does not have a type anyway), the type parameter is unnecessarily constrained to be sized:

image

The implicit Sized bound on T for the RangeXxx<&T> cases appears to be unintentional judging from the fact that there are no comments explaining this decision.

Meta

rustc --version --verbose:

rustc 1.66.1 (90743e729 2023-01-10)
binary: rustc
commit-hash: 90743e7298aca107ddaa0c202a4d3604e29bfeb6
commit-date: 2023-01-10
host: x86_64-unknown-linux-gnu
release: 1.66.1
LLVM version: 15.0.2
Backtrace

<backtrace>

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions