gpt4 book ai didi

recursion - 这种递归联接如何在Rust中工作

转载 作者:行者123 更新时间:2023-12-03 11:48:18 29 4
gpt4 key购买 nike

因此,我在Rust中编写了此递归字符串连接函数,该函数似乎有效,但是我有点困惑为什么它起作用。

fn join(separator: &str, strs: &[&str]) -> String {
match strs.len() {
l if l > 1 => return strs[0].to_string() + separator + &join(separator, &strs[1..]),
l if l == 1 => return strs[0].to_string(),
_ => return "".to_string(),
}
}
因此,我有一个要加入的3个字符串数组和一个字符串分隔符。该函数的第一个参数接受对str &str的引用,第二个参数接受对Strings &[&str]数组的引用。
let j1 = ["one", "two", "three"];
println!("{}", join(", ", &j1));
  • 为什么必须将递归联接定义为&join(separator, &strs[1..])
  • 为什么必须再次取消引用&strs[1..]
  • 最佳答案

  • std::ops::Add<&'_ str> is implemented for String (滚动到页面的最底部)。 std::ops::Add<String>不是。因此,只能在右侧添加&'_ strString。您必须引用对join的调用,因为它使用deref强制将String转换为&str
  • 为了给确切的证据提供更多的证据,但用最简单的话来说,切片(使用索引位置中的范围)切片或数组将产生切片IE,[T]。由于您无法传递裸[T],因此您需要对其进行引用。
    关于为什么的更确切的原因是:
  • Index<i> is impl-ed for [T] where I: SliceIndex<[T]>
  • 输出为 I 's output as a SliceIndex
  • 1..[std::ops::RangeFrom](https://doc.rust-lang.org/beta/std/ops/struct.RangeFrom.html)
  • SliceIndex<[T]> is impl-ed for all [T] on RangeFrom<usize>
  • 输出为[T]而不是&[T]


  • 此外,这不是编写此函数的最惯用的方式:
    pub fn join(separator: &str, strs: &[&str]) -> String {
    match strs {
    [last] => last.to_string(),
    [current, rest @ ..] => current.to_string() + separator + &join(separator, &rest),
    [] => "".to_string(),
    }
    }
    Pattern matching works on slices.

    关于recursion - 这种递归联接如何在Rust中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62767302/

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