Your current code might run into a couple of problems
-
i
is immutable, so even if your algorithm functions as intended, it can't change the data in i
- using
iter
or a for
loop iterates over the elements in the collection, you want the indices
Problem 1:
To index mutably and change elements like you have, you would need to change the signature to:
pub fn remove(i: &mut[isize])
Then, however, you wouldn't actually remove the elements – with a slice you could only replace them.
ProbIem 2:
When you call the method iter
to iterate over the slice i
:
for element in i.iter()
The type element is a reference to the items in the slice i
– in other words, a reference to the isize
elements in the slice.
Indexing
To index a slice (access its elements by their position, as you have done with []
notation) you must use a usize
, so it does not make sense to use the element
as an index. What you're doing is sort of like if you had typed:
let a = &['a', 'b', 'c'];
a['a'] // <- Instead of this you might want a[0]
Fix
@chrefr's answer is likely correct – You can use the dedup method, but you will need to create a Vec
from the slice (the slice is just a reference to a contiguous memory region, the Vec is a contiguous region but it has control over the contents):
pub fn remove(i:&[isize]){
let mut v = Vec::from_iter(i.iter().copied()); // copied was used to ensure v owns its data
v.sort(); // if your data wasn't already sorted, you would need to do this for dedup to work properly
v.dedup(); // you can also check out dedup_by and others
println!("{:?}",v);
println!("{:?}",i); // i has not changed!
// you would probably want to do something like return v here,
}
You might not even need a separate function for this option...
You can read more about what iter
does and see that it iterates over references in the documentation here: slice - Rust