miércoles, 28 de junio de 2023

Rust y Referencias colgantes


 Rust prohibirá las referencias colgantes:


fn main() {

    let ref_x: &i32;

    {

        let x: i32 = 10;

        ref_x = &x;

    }

    println!("ref_x: {ref_x}");

}


Se dice que una referencia "toma prestado" el valor al que se refiere.

Rust está rastreando la vida útil de todas las referencias para garantizar que vivan lo suficiente. Y lanza el siguiente error: 


$ cargo run

   Compiling hello_cargo v0.1.0 (/home/emanuel/Projects/rust/hello_cargo)

error[E0597]: `x` does not live long enough

  --> src/main.rs:9:17

   |

9  |         ref_x = &x;

   |                 ^^ borrowed value does not live long enough

10 |

11 |     }

   |     - `x` dropped here while still borrowed

12 |

13 |     println!("ref_x: {ref_x}");

   |                       ----- borrow later used here


For more information about this error, try `rustc --explain E0597`.

error: could not compile `hello_cargo` due to previous error


No hay comentarios.:

Publicar un comentario