Skip to content

Suggest implementing more traits for array type itself instead of using the traits of slice type #89067

Open
@SkyFan2002

Description

@SkyFan2002

We know that arrays can be automatically borrowed as slices,and it is convenient when we want to use a trait that has already been implemented for slices type.However,sometimes,when we want to use generics and the trait bounds,we will get into trouble.

I tried this code:

fn collection_len<T:len_trait::Len>(collection:&T) ->usize {
    collection.len()
}
fn main() {
    println!("{}",collection_len(&vec![1,2,3]));
    println!("{}",collection_len(&[1,2,3]));
}

I expected to see this happen:

3
3

Instead, this happened:

error[E0277]: the trait bound `[{integer}; 3]: Len` is not satisfied
 --> src/main.rs:6:34
  |
6 |     println!("{}",collection_len(&[1,2,3]));
  |                                  ^^^^^^^^ the trait `Len` is not implemented for `[{integer}; 3]`
  |
  = help: the following implementations were found:
            <[T] as Len>
note: required by a bound in `collection_len`
 --> src/main.rs:1:21
  |
1 | fn collection_len<T:len_trait::Len>(collection:&T) ->usize {
  |                     ^^^^^^^^^^^^^^ required by this bound in `collection_len`

The document:

impl<T> Len for [T]
impl Len for str
impl Len for CStr
impl Len for CString
impl Len for OsStr
impl Len for OsString
impl<K: Ord, V> Len for BTreeMap<K, V>
impl<T: Ord> Len for BTreeSet<T>
impl<T: Ord> Len for BinaryHeap<T>
impl<K: Eq + Hash, V> Len for HashMap<K, V>
impl<T: Eq + Hash> Len for HashSet<T>
impl<T> Len for LinkedList<T>
impl Len for String
impl<T> Len for Vec<T>
impl<T> Len for VecDeque<T>
impl Len for BitSet
impl Len for BitVec
impl<T> Len for BList<T>
impl<T: CLike> Len for EnumSet<T>
impl<T: Ord> Len for IntervalHeap<T>
impl<K: Eq, V> Len for LinearMap<K, V>
impl<K: Eq + Hash, V> Len for LinkedHashMap<K, V>
impl<K: Eq + Hash, V> Len for LruCache<K, V>
impl<T> Len for VecMap<T>

Maybe we can fix it by implementing more traits for array type. I wonder if we should change the automatical conversion,as the traits of array and those of slices may conflict.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`T-compilerRelevant to the compiler 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