您正在寻找str::splitn
:
fn split_once(in_string: &str) -> (&str, &str) {
let mut splitter = in_string.splitn(2, ':');
let first = splitter.next().unwrap();
let second = splitter.next().unwrap();
(first, second)
}
fn main() {
let (a, b) = split_once("hello:world:earth");
println!("{} --- {}", a, b)
}
请注意,Rust 使用snake_case
.
我猜这是因为拆分器只存在于功能块内部
不,这是因为你创建了一个String
,并试图返回对它的引用;you cannot do that.second
是活得不够长的东西.
如何强制second
超越功能块?
你没有.这是Rust 的一个基本方面.如果某样东西需要活一段时间,你就just have to make it exist for that long.在本例中,与链接问题一样,您将返回String
:
fn split_once(in_string: &str) -> (&str, String) {
let mut splitter = in_string.split(':');
let first = splitter.next().unwrap();
let second = splitter.fold("".to_string(), |a, b| a + b);
(first, second)
}