在 Rust 中只拆分一次字符串 [英] Split string only once in Rust
问题描述
我只想通过分隔符将字符串拆分一次并将其放入元组中.我试着做
I want to split a string by a separator only once and put it into a tuple. I tried doing
fn splitOnce(in_string: &str) -> (&str, &str) {
let mut splitter = in_string.split(':');
let first = splitter.next().unwrap();
let second = splitter.fold("".to_string(), |a, b| a + b);
(first, &second)
}
但我一直被告知 second
的寿命不够长.我猜这是因为 splitter
只存在于功能块内,但我不确定如何解决这个问题.如何强制 second
超出功能块的存在?或者有没有更好的方法将字符串只拆分一次?
but I keep getting told that second
does not live long enough. I guess it's saying that because splitter
only exists inside the function block but I'm not really sure how to address that. How to I coerce second
into existing beyond the function block? Or is there a better way to split a string only once?
推荐答案
您正在寻找 str::splitn
:
You are looking for 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
.
Note that Rust uses snake_case
.
我猜是因为splitter只存在于功能块内
I guess it's saying that because splitter only exists inside the function block
不,这是因为您创建了一个 String
并试图返回对它的引用;你不能这样做.second
是活得不够久.
Nope, it's because you've created a String
and are trying to return a reference to it; you cannot do that. second
is what doesn't live long enough.
如何将second
强制转换为存在于功能块之外?
How to I coerce
second
into existing beyond the function block?
你没有.这是 Rust 的一个基本方面.如果某样东西需要存活一段时间,你只需要让它存在那么久.在这种情况下,就像在链接的问题中一样,您将返回 String
:
You don't. This is a fundamental aspect of Rust. If something needs to live for a certain mount of time, you just have to make it exist for that long. In this case, as in the linked question, you'd return the 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)
}
这篇关于在 Rust 中只拆分一次字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!