gpt4 book ai didi

string - 如何传递 &mut str 并更改原始 mut str 而不返回?

转载 作者:行者123 更新时间:2023-12-03 11:34:06 25 4
gpt4 key购买 nike

我正在从书中学习 Rust,并且我正在处理第 8 章末尾的练习,但是关于将单词转换为 Pig Latin 的练习我遇到了困难。我想具体看看我是否可以将 &mut String 传递给一个接受 &mut str 的函数(也接受切片)并修改其中的引用字符串,以便更改不需要 return 就可以反射回外部,就像在 C 中使用 char **

我不太确定我是否只是弄乱了语法,或者由于 Rust 的严格规则,它是否比听起来更复杂,我还没有完全掌握。对于 to_pig_latin() 中的生命周期错误,我记得读过一些解释如何正确处理这种情况的东西,但现在我找不到它,所以如果你也可以为我指出它会是非常感谢。

另外,您如何看待我处理字符串中的字符和索引的方式?

use std::io::{self, Write};

fn main() {
let v = vec![
String::from("kaka"),
String::from("Apple"),
String::from("everett"),
String::from("Robin"),
];

for s in &v {
// cannot borrow `s` as mutable, as it is not declared as mutable
// cannot borrow data in a `&` reference as mutable
to_pig_latin(&mut s);
}

for (i, s) in v.iter().enumerate() {
print!("{}", s);

if i < v.len() - 1 {
print!(", ");
}
}

io::stdout().flush().unwrap();
}

fn to_pig_latin(mut s: &mut str) {
let first = s.chars().nth(0).unwrap();
let mut pig;

if "aeiouAEIOU".contains(first) {
pig = format!("{}-{}", s, "hay");
s = &mut pig[..]; // `pig` does not live long enough
} else {
let mut word = String::new();

for (i, c) in s.char_indices() {
if i != 0 {
word.push(c);
}
}

pig = format!("{}-{}{}", word, first.to_lowercase(), "ay");
s = &mut pig[..]; // `pig` does not live long enough
}
}

编辑:这是带有以下建议的固定代码。

fn main() {
// added mut
let mut v = vec![
String::from("kaka"),
String::from("Apple"),
String::from("everett"),
String::from("Robin"),
];

// added mut
for mut s in &mut v {
to_pig_latin(&mut s);
}

for (i, s) in v.iter().enumerate() {
print!("{}", s);

if i < v.len() - 1 {
print!(", ");
}
}

println!();
}

// converted into &mut String
fn to_pig_latin(s: &mut String) {
let first = s.chars().nth(0).unwrap();

if "aeiouAEIOU".contains(first) {
s.push_str("-hay");
} else {
// added code to make the new first letter uppercase
let second = s.chars().nth(1).unwrap();

*s = format!(
"{}{}-{}ay",
second.to_uppercase(),
// the slice starts at the third char of the string, as if &s[2..]
&s[first.len_utf8() * 2..],
first.to_lowercase()
);
}
}

最佳答案

I'm not quite sure if I'm just messing up the syntax or if it's more complicated than it sounds due to Rust's strict rules, which I have yet to fully grasp. For the lifetime errors inside to_pig_latin() I remember reading something that explained how to properly handle the situation but right now I can't find it, so if you could also point it out for me it would be very appreciated.

您尝试做的事情是行不通的:使用可变引用,您可以就地更新裁判,但这在这里非常有限:

  • 一个 &mut str 不能改变长度或任何类似的事情
  • a &mut str 仍然只是一个引用,内存必须存在于某个地方,在这里你在你的函数中创建新的字符串,然后尝试将它们用作引用的新后备缓冲区,正如编译器告诉你的那样不起作用:字符串将在函数结束时被释放

您可以做的是采用 &mut String,它可以让您就地修改拥有的字符串本身,这更加灵活。而且,实际上,完全符合您的要求:一个 &mut str 对应一个 char*,它是指向内存中某个位置的指针。

String 也是一个指针,所以 &mut String 是一个指向内存区域的双指针。

所以是这样的:

fn to_pig_latin(s: &mut String) {
let first = s.chars().nth(0).unwrap();
if "aeiouAEIOU".contains(first) {
*s = format!("{}-{}", s, "hay");
} else {
let mut word = String::new();

for (i, c) in s.char_indices() {
if i != 0 {
word.push(c);
}
}

*s = format!("{}-{}{}", word, first.to_lowercase(), "ay");
}
}

您还可以通过使用更精细的方法来避免一些完整的字符串分配,例如

fn to_pig_latin(s: &mut String) {
let first = s.chars().nth(0).unwrap();
if "aeiouAEIOU".contains(first) {
s.push_str("-hay")
} else {
s.replace_range(first.len_utf8().., "");
write!(s, "-{}ay", first.to_lowercase()).unwrap();
}
}

虽然 replace_range + write! 的可读性不是很好,也不太可能有很大的收获,所以这也可能是一个 格式! ,类似于:

fn to_pig_latin(s: &mut String) {
let first = s.chars().nth(0).unwrap();
if "aeiouAEIOU".contains(first) {
s.push_str("-hay")
} else {
*s = format!("{}-{}ay", &s[first.len_utf8()..], first.to_lowercase());
}
}

关于string - 如何传递 &mut str 并更改原始 mut str 而不返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63131868/

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