gpt4 book ai didi

rust - 将 char 附加到使用rust 的字符串

转载 作者:行者123 更新时间:2023-11-29 08:06:57 25 4
gpt4 key购买 nike

<分区>

文档 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;

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com