The following code in Rust compiles fine:
pub fn insertion_sort(data : &mut [int]){
let n = data.len();
for j in range(1, n){
let key = data[j];
// we insert data[j] into the sorted sequence
//data[0...j-1]
let mut i = j -1;
while data[i] > key{
data[i + 1] = data[i];
if i == 0{
break;
}
i -= 1;
}
data[i] = key;
}
}
But the moment, I introduce generics as follows:
pub fn insertion_sort<T : Ord>(data : &mut [T]){
let n = data.len();
for j in range(1, n){
let key = data[j];
// we insert data[j] into the sorted sequence
//data[0...j-1]
let mut i = j -1;
while data[i] > key{
data[i + 1] = data[i];
if i == 0{
break;
}
i -= 1;
}
data[i] = key;
}
}
the compiler reports following problems:
error: cannot move out of dereference of
&mut-pointer insertion.rs:6 let key = data[j];error: cannot move out of dereference of
&mut-pointer insertion.rs:11 data[i + 1] = data[i];
Do we need to take some special care while moving from a non-generic code for built-in types to generic code? The error messages sound quite cryptic.
[EDIT]
Based on Vladimir's advice below, I have attempted to come up with a version which can work for T : Ord using swap functions of a slice
pub fn insertion_sort<T : Ord>(data : &mut [T]){
let n = data.len();
for j in range(1, n){
// we insert data[j] into the sorted sequence
//data[0...j-1]
let mut i = j -1;
while data[i] > data[i+1]{
data.swap(i + 1, i);
if i == 0{
break;
}
i -= 1;
}
}
}