我需要将String
(不是&str
)与另一个String
分开:
use std::str::Split;
fn main() {
let x = "".to_string().split("".to_string());
}
为什么我会遇到此错误以及如果我必须对字符串进行操作,如何避免它?
error[E0277]: the trait bound `std::string::String: std::ops::FnMut<(char,)>` is not satisfied
--> src/main.rs:4:32
|
4 | let x = "".to_string().split("".to_string());
| ^^^^^ the trait `std::ops::FnMut<(char,)>` is not implemented for `std::string::String`
|
= note: required because of the requirements on the impl of `std::str::pattern::Pattern<'_>` for `std::string::String`
根据#stix-beginners IRC频道,这可能是Deref
在1.20.0-夜间失败的一个例子。 How to split a string in Rust?没有解决按String
分割的问题,而不是&str
。
答案 0 :(得分:6)
全部都在documentation。您可以提供以下其中一项:
&str
,char
,这三种类型实现Pattern
特征。您将String
提供给split
而不是&str
。
示例:
fn main() {
let x = "".to_string();
let split = x.split("");
}
答案 1 :(得分:3)
我和#stix-beginners IRC频道讨论了这个问题并听取了以下内容:
15:12:15 achird | d33tah: split accepts a Pattern, where Pattern can be &str or char, but you're passing a String (no idea why deref is not working)
15:13:01 d33tah | achird: thanks! how can I convert string to str?
15:13:03 achird | i think a simple split(&delimiter2) should fix the problem
15:16:26 calops | why isn't deref working though?
15:21:33 @mbrubeck | calops, d33tah: Deref coercions only work if one exact "expected" type is known. For a generic type like <P: Pattern>, coercion doesn't kick in.
15:24:11 @mbrubeck | d33tah: The error should definitely be improved... It should complain that `String` doesn't impl `Pattern`, instead of jumping straight to `FnMut(char)`
基本上,解决方案是添加&amp;在分隔符字符串之前,如下所示:
fn main() {
let s1 = "".to_string();
let s2 = "".to_string();
let x = s1.split(&s2);
}