使用同一结构的另一个字段初始化结构的字段 [英] Initialize a field of a struct using another field of the same struct

查看:54
本文介绍了使用同一结构的另一个字段初始化结构的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面我有一个结构SplitByChars.

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: I cannot use self here!
        }
    }
}

我正在尝试为它实现一个 new 静态函数.特别是,我想返回一个 SplitByChars 实例,它的 chars_iter 字段是使用同一实例的先前初始化的 string 字段初始化的.为此,我目前正尝试使用 self.string 访问同一字段,但出现错误.

I am trying to implement a new static function for it. In particular, I would like to return a SplitByChars instance whose chars_iter field is initialized using the previously initialized string field of the same instance. To do that, I am currently trying to access the same field using self.string, but I am getting an error.

我该怎么做?

推荐答案

我该怎么做?

你不能.除非我误解了您的问题,否则这与 这个问题相同.结构通常不能对自身进行引用.

You can't. Unless I misunderstand your question, this is the same problem as this one. Structs generally cannot have references into themselves.

这篇关于使用同一结构的另一个字段初始化结构的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆