gpt4 book ai didi

rust - 如何在Rust中返回链式迭代器

转载 作者:行者123 更新时间:2023-12-03 11:45:33 26 4
gpt4 key购买 nike

我有一个简单的结构,用于定义要通过网络发送的某种消息。

struct Message {
message_type: u32,
user_id: u32,
message: Vec<u8>,
}

在其他地方,我想将其序列化为一个简单的字节序列。因此,我为消息的字节定义了迭代器,如下所示:

impl Message {
fn iter(&self) -> std::iter::Chain<std::iter::Chain<std::slice::Iter<'_, u8>, std::slice::Iter<'_, u8>>, std::slice::Iter<'_, u8>> {
self.message_type
.to_be_bytes()
.iter()
.chain(self.user_id.to_be_bytes().iter())
.chain(self.message.iter())
}

fn data(&self) -> Vec<u8> {
self.iter().cloned().collect()
}
}

是的,类型随着链式迭代器的增加而不断增长,这实在令人遗憾

但是我尝试运行它时遇到2个编译器错误
cannot return value referencing temporary value

returns a value referencing data owned by the current function. rustc(E0515)

猜猜我对 rust 的所有权系统不了解

最佳答案

使用rust 借阅检查器提示的问题是因为to_be_bytes()函数返回存储在堆栈中的数组。该代码正在尝试为在堆栈上分配的对象创建一个迭代器,而该迭代器使该对象失效。

self.message_type.to_be_bytes()

例如:
这将在堆栈上创建一个数组,并且 .iter()仅在该对象存在的情况下才有效。

有几种方法可以解决此问题。在同一函数中将iter最终转换为字节。
fn data(&self) -> Vec<u8> {
self.message_type
.to_be_bytes()
.iter()
.chain(self.user_id.to_be_bytes().iter())
.chain(self.message.iter()).map(|x| *x).collect()
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=129af6e7da3d1e3a9454fffbb124e170

Caution: Whenever you convert to bytes, confirm whether you want little endian/big endian and all the bytes follow the same endianess.

关于rust - 如何在Rust中返回链式迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61853531/

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