【问题标题】:Initialize a field of a struct using another field of the same struct [duplicate]使用同一结构的另一个字段初始化结构的字段[重复]
【发布时间】:2015-08-03 18:41:38
【问题描述】:

下面我有一个结构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 访问同一字段,但出现错误。

我该怎么做?

【问题讨论】:

    标签: rust


    【解决方案1】:

    我该怎么做?

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

    【讨论】:

    • 好的,我了解设计。但是,对于需要引用自身的结构的设计有什么帮助吗?我怎样才能重新设计我的结构来满足这个需求?
    【解决方案2】:

    我认为你让事情变得过于复杂。可以通过以下方式在特定字符处拆分字符串:

    let s: String = "Tiger in the snow".into();
    for e in s.split(|c| c == 'e') {
        println!("{}", e);
    }
    

    输出:

    Tig
    r in th
     snow
    

    拆分功能有多种变体以满足各种需求。

    【讨论】:

    • 我不是要求拆分字符串,我认为在某些情况下您需要在结构中引用自己。
    猜你喜欢
    • 2021-12-28
    • 2019-10-05
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多