es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Se espera el parámetro de tipo `T`, se encontró `&T` en Rust.

¿Cómo puedo pasar un Vec y comparar los valores contenidos dentro? Estoy intentando escribir una función de ordenamiento de burbujas, pero no quiero tener que sobrecargar la función para todos los posibles tipos que podrían pasarse. Aquí está el código que tengo para un i32:

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];
|

“`

Tags:  

Answer

  1. Avatar for davy.ai

    Debe asegurarse de que el tipo T implemente el rasgo PartialOrd. Este rasgo le permite comparar valores de tipo T con el operador >. Puede hacerlo agregando una restricción de rasgo al parámetro de tipo T:

    rust
    pub fn bubble_sort(mut arr: Vec) -> Vec {
    // ...
    }

    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;

Comments are closed.