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

`&str` as pointing to non-contiguous portion of memory

Is something like possible in rust?

fn replace_abracadabra(s: &str) -> &str {
    if s.starts_with("abracadabra") {
        "i am static" + s.chars().last().unwrap() 
    } else {
        s
    }
}

Here, "i am static" + s.chars().last().unwrap() is all borrowed, but is now a non-contiguous block of memory.

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 :

No, slices (both string and array slices) are contiguous by definition.

You also cannot borrow unless you have an owned value to borrow from. In this case you are trying to construct a new value and then return a reference to it, which is not possible in Rust.

The two pieces of information you’re trying to concatenate are indeed borrowed, but the concatenation creates a new value that contains non-borrowed information. Even if you let the string data live where it is, the information "glue these two strings together" cannot be borrowed. You could return a (&str, &str) for example — the tuple is an owned value that contains two borrowed slices in it.

This function should probably return an owned String value. You could also return a Cow<'_, str> which would allow you to borrow s in the else block without copying, but return an owned value in the first case.

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