gpt4 book ai didi

rust - 字符串切片vs切片&String

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

我正在阅读rust lang网站上的文档,在第4章中,他们做了以下示例:

let s = String::from("hello world");

let hello = &s[0..5];
let world = &s[6..11];
hello是我从 &str类型的 s变量创建的 String类型的。
它们下面的一些行定义了以下功能:
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();

for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}

&s[..]
}
这次 s的类型为 &String,但 &s[0..i]仍然为我提供了 &str切片。
这怎么可能?我认为实现此目标的正确方法将类似于 &((*str)[0..i])
我想念什么吗?也许在 [0..i]操作期间Rust自动引用了变量?
谢谢

最佳答案

Maybe during the [0..i] operation Rust auto deference the variable?


这正是发生的情况。当您调用方法/索引引用时,它会在应用方法之前自动取消引用。也可以使用 Deref特性手动实现此行为。 String的目标是 Deref来实现 str,这意味着当您在 str上调用 String方法时。阅读有关deref coercion here的更多信息。

关于rust - 字符串切片vs切片&String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63292739/

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