gpt4 book ai didi

string - “` str` does not have a constant size known at compile-time”是什么意思,最简单的修复方法是什么?

转载 作者:行者123 更新时间:2023-11-29 07:46:04 26 4
gpt4 key购买 nike

我正在尝试操作从函数参数派生的字符串,然后返回该操作的结果:

fn main() {
let a: [u8; 3] = [0, 1, 2];
for i in a.iter() {
println!("{}", choose("abc", *i));
}
}

fn choose(s: &str, pad: u8) -> String {
let c = match pad {
0 => ["000000000000000", s].join("")[s.len()..],
1 => [s, "000000000000000"].join("")[..16],
_ => ["00", s, "0000000000000"].join("")[..16],
};
c.to_string()
}

在构建时,我收到此错误:

error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
--> src\main.rs:9:9
|
9 | let c = match pad {
| ^ `str` does not have a constant size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `str`
= note: all local variables must have a statically known size

这里出了什么问题,最简单的修复方法是什么?

最佳答案

TL;DR 不要使用 str , 使用 &str .引用很重要。


问题可以简化为:

fn main() {
let demo = "demo"[..];
}

您正在尝试切片 &str (但对于 String&[T]Vec<T> 等也会发生同样的情况),但没有引用结果。这意味着 demo 的类型将是 str .要修复它,请添加 & :

let demo = &"demo"[..];

在更广泛的示例中,您还遇到了这样一个事实,即您正在创建一个已分配的 Stringmatch里面语句(通过 join ),然后尝试返回对它的引用。这是不允许的,因为 String将在 match 的末尾删除,使任何引用无效。在另一种语言中,这可能会导致内存不安全。

一个潜在的解决方法是存储创建的 String在函数运行期间,防止在创建新字符串之前释放它:

fn choose(s: &str, pad: u8) -> String {
let tmp;

match pad {
0 => {
tmp = ["000000000000000", s].join("");
&tmp[s.len()..]
}
1 => {
tmp = [s, "000000000000000"].join("");
&tmp[..16]
}
_ => {
tmp = ["00", s, "0000000000000"].join("");
&tmp[..16]
}
}.to_string()
}

在编辑方面,可能有更有效的方法来编写此函数。 formatting machinery有填充字符串的选项。您甚至可以截断从 join 返回的字符串无需创建新的。


它的含义很难简洁地解释。 Rust 有许多未调整大小的类型。最普遍的是 str[T] .将这些类型与您通常看到的它们的使用方式进行对比:&str&[T] .您甚至可能将它们视为 Box<str>Arc<[T]> .共同点是它们总是在某种引用后面使用。

因为这些类型没有大小,所以它们不能存储在堆栈上的变量中——编译器不知道要为它们保留多少堆栈空间!这就是错误消息的本质。

另见:

关于string - “` str` does not have a constant size known at compile-time”是什么意思,最简单的修复方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49393462/

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