clamentjohn
clamentjohn

Reputation: 3987

Passing a string slice, returning a string slice. But who owns it?

I'm a beginner to Rust and just learning the ownership concept.

I'm using this function to reverse a String

fn reverse(input: &str) -> String {
    //we are receiving a borrowed value, 
    input
    //get an iterator of chars from the string slice
    .chars()
    //Goes between two iterators. 
    //From the doc:  double-ended iterator with the direction inverted.
    .rev()
    //collect into a String
    .collect::<String>()
}

fn process_reverse_case(input: &str, expected: &str) {
    assert_eq!(&reverse(input), expected)
}

fn main() {
    process_reverse_case("robot", "tobor");
}

I would like to understand who owns robot and tobor.

Upvotes: 1

Views: 467

Answers (1)

hellow
hellow

Reputation: 13430

Your claims are mostly wrong, let me try to correct them.

Passing a string slice, returning a string slice

fn reverse(input: &str) -> String you are accepting a string slice, but returning a String. A String "has ownership over the contents of the string".


I understand this [a string slice] can't be modified

You can modify a &mut str, e.g.

fn to_lower(s: &mut str) {
    s.make_ascii_lowercase();
}

fn main() {
    let mut a = String::from("ABC");
    println!("{}", a);
    to_lower(&mut a);
    println!("{}", a);
}

(playground)


So when we are collecting the reversed string, I think we are collecting it into a argument 1 of assert_eq!

No. You collect it into a string, that is what collect::<String>() is for. Also your function reverse returns a String.
This means, that you are calling the function reverse, which returns a String and you are passing that String as the first "argument" to the assert_eq! macro.


the memory needed keeps increasing. Does argument 1 of assert_eq! account for that?

No, how should it? That's all done inside of the reverse function. assert_eq! just takes two parameters. Where they come from is uncertain and not needed to know.


assert_eq!(&reverse(input), expected)

What happens in this line is, that you are calling your reverse function with input as parameter. But normally you can't compare &T with T (a reference to something with an actual instance of something), that's where the & (ampersand) in front of reverse comes into play. String implements the Deref trait which means it can be seen as a str as well (see the doc for Deref). But now you are trying to compare a str with &str, which does not work and that's why you put & in front, so you actually end up with &str and &str which you can compare with ==.


I would like to understand who ownes robot and tobor.

Nobody. In fact they live inside of the data section in the ELF/Binary itself. They don't have an owner per se, but can be used as &str wherever needed.

Upvotes: 5

Related Questions