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.
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.
No problem, I was posting the link so that people don’t need to come up with answers twice in case something was already said in one thread. Not to criticize your decision to re-post in this forum.
Also, your code-formatting is broken here, while things are readable on github. (In case you don’t know how to fix that, see this post in the users forum.)