当我需要引用自身时如何设计结构 [英] How to design a struct when I need to reference to itself
问题描述
我的上一个问题告诉我 Rust 不能在结构中引用自身.
My previous question tells me that Rust cannot take reference to itself in a struct.
所以我的问题就变成了:当我需要引用自身时如何设计结构?
So my question would become: how to design a struct when I need to reference to itself?
我们可以以这个结构体为例:
We might take this struct as an example:
struct SplitByChars<'a> {
seperator: &'a Seperator,
string: String,
chars_iter: std::str::Chars<'a>,
}
impl<'a> SplitByChars<'a> {
fn new<S>(seperator: &'a Seperator, string: S) -> SplitByChars where S: Into<String> {
SplitByChars {
seperator: seperator,
string: string.into(),
chars_iter: self.string.chars(), // error here: I cannot use self (of course, static method)
}
}
}
我使用了 chars_iter
来提供可迭代字符串拆分的接口.
I used chars_iter
to provide an interface of iterable string splitting.
(这只是一个例子,所以我想知道关于设计结构的更一般的想法,而不是特别在这种拆分情况下.此外,没有 std 的拆分.)
(This is just an example, so I'd like to know about a more general idea on designing the struct, not specially in this splitting case. Moreover, no std's split.)
推荐答案
虽然一个字段不能引用结构中的另一个字段,但你通常可以通过移动来实现您的需求.它的工作原理是将一个字段作为数据另一个字段作为 Option
包含一些按值获取该数据的结构(并实现一些您感兴趣的特征).
While a field cannot reference another field within a struct, you can usually
achieve what you need by moving them. It works by having one field as data
and another field as an Option
containing some struct taking that data by value
(and implementing some trait of your interest).
您可以在 this answer 中找到实施 ittaror 适配器的示例,其中数据是 HashMap
,Option
包含地图的 IntoIter
.在迭代期间,一旦不再需要访问地图,使用 std::mem::replace
移动到 IntoIter
.
You can find the example in this answer implementing an itetaror adaptor,
where the data was a HashMap
and the Option
contained the map's IntoIter
.
During the iteration once the access to the map was no longer needed, it was
moved into IntoIter
using std::mem::replace
.
但是,在您的特定情况下,std
中没有方法可以通过消耗String
(即使用self
作为参数)来创建Chars
迭代器.您必须自己实施.
However, in your specific case there is no method in std
that would
create Chars
iterator by consuming the String
(i.e. using self
as an argument). You would have to implement it yourself.
这篇关于当我需要引用自身时如何设计结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!