【问题标题】:Appending a char to a string in rust [duplicate]将字符附加到 rust 中的字符串 [重复]
【发布时间】:2014-05-21 22:29:46
【问题描述】:

文档here 定义了一个特征,其中包括一个方法push_char,它接受一个可变的self 并向其附加一个字符。但是,此代码失败:

fn foo() {
  let mut s = "hey".to_owned();
  s.push_char('!');
}

正在尝试编译:

$ rustc --version
rustc 0.11-pre (e8053b9 2014-05-12 09:12:04 -0700)
host: x86_64-apple-darwin
$ rustc appendchar.rs
appendchar.rs:5:5: 5:19 error: type `~str` does not implement any method in scope named `push_char`
appendchar.rs:5   s.push_char('!');
                    ^~~~~~~~~~~~~~
error: aborting due to previous error

所以我们可以看到s 确实是~str 类型,并且根据文档,这种类型实现了OwnedStr。那么为什么会失败呢?顺便说一句,添加以下行并不能解决它:

use std::str::OwnedStr;

【问题讨论】:

    标签: rust traits


    【解决方案1】:

    我假设您使用的是 0.10 文档和主版本。为迎接动态大小类型的新世界做准备,~str(又名Box<str>)不包含容量,而只有长度,因此无法有效地推送到每次都需要重新分配,those methods have been removed from OwnedStr。现在你应该处理StrBuf,它有push_char之类的方法。

    【讨论】:

      猜你喜欢
      • 2015-07-25
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 2012-05-28
      相关资源
      最近更新 更多