Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does rust deal with the ownership of the returned string?

This is the code I have:

fn test_function() -> String {
    String::from("")
}

fn main() {
    test_function();
    println!("Hello");
}

I was expecting rust to complain about test_function return value not being assigned, but it just works.

How are the rules of ownership applied here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I was expeting rust to complain about test_function return value not being assigned, but it just works.

Why would it complain? Rust’s type system is affine, meaning values can be used at most once. Using them 0 times is valid (you can mark types and functions as #[must_use] to trigger a warning, but even then a simple let _ = ... will silence it)

How are the rules of ownership applied here?

The string is moved out of the function, then dropped by the caller since nothing is keeping it alive.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading