Se espera el parámetro de tipo `T`, se encontró `&T` en Rust.
¿Cómo puedo pasar un Vec
pub fn bubble_sort(mut arr: Vec<i32>) -> Vec<i32>
{
for i in 1..(arr.len() - 1)
{
for j in 0..(arr.len() - i)
{
if j == arr.len() - 1 { continue; }
if arr[j] > arr[j + 1]
{
let buffer = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = buffer;
}
}
}
return arr;
}
Intenté hacer lo siguiente:
pub fn bubble_sort<t>(mut arr: Vec<t>) -> Vec<t>
{
for i in 1..(arr.len() - 1)
{
for j in 0..(arr.len() - i)
{
if j == arr.len() - 1 { continue; }
if arr[j] > arr[j + 1]
{
let buffer = &arr[j + 1];
arr[j + 1] = &arr[j];
arr[j] = buffer;
}
}
}
return arr;
}
Pero obtengo el siguiente error:
error[E0369]: binary operation > cannot be applied to type T
--> src/bubblesort.rs:8:23
|
8 | if arr[j] > arr[j + 1]
| ------ ^ ---------- T
| |
| T
|
help: consider restricting type parameter T
|
1 | pub fn bubblesort<t: std::cmp::partialord="">(mut arr: Vec<t>) -> Vec<t>
| ++++++++++++++++++++++
Intenté hacer eso, sin embargo, obtengo el siguiente error:
“`none
error[E0308]: mismatched types
–> src/bubblesort.rs:10:30
|
1 | pub fn bubblesort<t: std::cmp::partialord="">(mut arr: Vec<t>) -> Vec<t>{
| – this type parameter
…
10 | arr[j + 1] = &arr[j];
| ^^^^^^^ expected type parameter T, found &T
|
= note: expected type parameter T
found reference &T
help: consider removing the borrow
|
10 – arr[j + 1] = &arr[j];
10 + arr[j + 1] = arr[j];
|
“`
davy.ai
Debe asegurarse de que el tipo
T
implemente el rasgoPartialOrd
. Este rasgo le permite comparar valores de tipoT
con el operador>
. Puede hacerlo agregando una restricción de rasgo al parámetro de tipoT
:rust(mut arr: Vec) -> Vec {
pub fn bubble_sort
// ...
}
También es necesario asegurarse de que no esté intentando asignar una referencia a los elementos del arreglo. Puede hacerlo eliminando el símbolo
&
de la asignación:rust
let buffer = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = buffer;