gpt4 book ai didi

arrays - 如何在 Rust 中映射数组引用

转载 作者:行者123 更新时间:2023-11-29 08:24:41 25 4
gpt4 key购买 nike

我有这个数组

let buffer: &[u8] = &[0; 40000];

但是当我想这样映射它时:

*buffer.map( |x| 0xff);

我有以下错误:

error[E0599]: no method named `map` found for type `&[u8]` in the current scope   
--> src/bin/save_png.rs:12:13
|
12 | *buffer.map( |x| 0xff); //.map(|x| 0xff);
| ^^^
|
= note: the method `map` exists but the following trait bounds were not satisfied:
`&mut &[u8] : std::iter::Iterator`
`&mut [u8] : std::iter::Iterator`

我尝试了几种方法来使元素可变,但我无法获得正确的语法。任何人有经验吗?我正在尝试使用 png 图像缓冲区。

最佳答案

类型 &[T] 没有 map 方法。如果您查看错误消息,它告诉您存在一个名为 map 的方法,但它不适用于 &mut &[u8]&mut [ u8] 因为这些类型没有实现 Iterator。数组和其他集合通常有一个或一组方法来创建迭代器。对于切片或数组,您可以选择 iter()(迭代引用)或 into_iter()(迭代移动的值并使用源集合) .

通常,您还希望将这些值收集到其他集合中:

let res: Vec<u8> = buffer
.iter()
.map(|x| 0xff)
.collect();

关于arrays - 如何在 Rust 中映射数组引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53561870/

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