如何在Rust中映射数组引用

9

我有一个数组

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图像缓冲。

1个回答

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

通常,您还需要将值收集到其他集合中:

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

3
你可以得到一个数组返回,而不是转换为 Vec 吗? - User
1
@Ixx,你无法获取一个数组,因为 .collect() 不知道输入的长度,在 Rust 中数组是固定长度的。你可以查看所有可以收集的东西,通过查看哪些实现了 FromIterator 接口:https://doc.rust-lang.org/std/iter/trait.FromIterator.html#implementors - Kevin M Granger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接