【问题标题】:How can I concatenate two string fields with another string?如何将两个字符串字段与另一个字符串连接起来?
【发布时间】:2015-10-31 15:50:43
【问题描述】:

我不明白 Rust 如何处理字符串。我创建了一个带有两个字符串字段和一个方法的简单结构。此方法连接两个字段和参数中的字符串。我的代码:

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
    }
}

运行时出现错误:

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.

我从 Rust 书中读到了 this chapter。我尝试像代码示例中那样连接字符串,但编译器说它不是字符串。

我在网上搜索过,但没有 Rust 1.3 的示例。

【问题讨论】:

  • stackoverflow.com/questions/30154541/… 或 stackoverflow.com/questions/31331308/… 的重复项?如果你不同意,你应该edit你的问题来澄清为什么它不是重复的。
  • @Shepmaster 是的,你是对的。这是类似的问题。但是你的问题是关于函数和字符串的。我询问了方法和字符串字段。我也遇到了生命周期问题,我尝试使用'a 来解决它。 @lllogiq 向我展示了如何在没有它的情况下连接字符串字段。

标签: string struct rust string-concatenation


【解决方案1】:

您尝试连接两个指向字符串的指针,但这不是 Rust 中字符串连接的工作方式。它的工作方式是使用第一个字符串(您必须按值传递那个字符串)并返回使用第二个字符串切片的内容扩展的使用的字符串。

现在做你想做的最简单的方法是:

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

注意这也会创建一个新的拥有的字符串,因为不可能从创建字符串的作用域返回一个字符串的字符串引用——它将在作用域结束时被销毁,除非它是按值返回的.

【讨论】:

  • 为什么你认为这个问题不是上面评论中可能出现的问题之一的重复?
  • @lllogiq 现在我明白了。谢谢。
  • @Shepmaster,我一定忽略了他们。
猜你喜欢
  • 1970-01-01
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-02
  • 2017-05-30
  • 2017-03-25
相关资源
最近更新 更多