1

I can't understand how Rust works with strings. I created a simple struct with two string fields and one method. This method concatenates both fields and the string from arguments. My code:

fn main() {
    let obj = MyStruct {
        field_1: "first".to_string(),
        field_2: "second".to_string(),
    };

    let data = obj.get_data("myWord");
    println!("{}",data);
}

struct MyStruct {
    field_1: String,
    field_2: String,
}

impl MyStruct {
    fn get_data<'a>(&'a self, word: &'a str) -> &'a str {
        let sx = &self.field_1 + &self.field_2 + word;
        &* sx
    }
}

I get an error when run it:

src\main.rs:18:18: 18:31 error: binary operation `+` cannot be applied to type `&collections::string::String` [E0369]
src\main.rs:18         let sx = &self.field_1 + &self.field_2 + word;
                                ^~~~~~~~~~~~~
src\main.rs:19:10: 19:14 error: the type of this value must be known in this context
src\main.rs:19         &* sx
                        ^~~~
error: aborting due to 2 previous errors
Could not compile `test`.

To learn more, run the command again with --verbose.

I read this chapter from the Rust book. I try to concatenate strings like in code example, but the compiler says that it's not a string.

I searched online, but there were no examples for Rust 1.3.

Haru Atari
  • 1,502
  • 2
  • 17
  • 30
  • 2
    Duplicate of http://stackoverflow.com/questions/30154541/how-do-i-concatenate-strings or http://stackoverflow.com/questions/31331308/what-is-the-standard-way-to-concatenate-strings? If you disagree, you should [edit] your question to clarify why it is not a duplicate. – Shepmaster Oct 30 '15 at 20:21
  • @Shepmaster Yes you are right. This is similar questions. But your questions ask about function and strings. I asked about method and string fields. I also had problems with lifetime and i try to solve it by using `'a`. @llogiq shown me how concatenate string fields without it. – Haru Atari Oct 31 '15 at 07:45

1 Answers1

5

You try to concatenate two pointers to strings, but this is not how string concatenation works in Rust. The way it works is that it consumes the first string (you have to pass that one in by value) and returns the consumed string extended with the contents of the second string slice.

Now the easiest way to do what you want is:

fn get_data(&self, word: &str) -> String {
    format!("{}{}{}", &self.field_1, &self.field_2, word)
}

Note that will also create a new owned String, because it is impossible to return a String reference of a String from the scope that created the String – it will be destroyed at the end of the scope, unless it is returned by value.

llogiq
  • 13,815
  • 8
  • 40
  • 72