【问题标题】:How to compare &self in struct's method with another struct如何将结构方法中的 &self 与另一个结构进行比较
【发布时间】:2019-07-10 19:25:41
【问题描述】:

我不知道为什么,但我的方法不起作用,有没有办法将 self 与其父结构进行比较?我为上下文添加了数据结构。

#[derive(PartialEq, Copy, Clone, Debug)]
enum Suits {
    Hearts,
    Spades,
    Clubs,
    Diamonds,
}

#[derive(PartialEq, Copy, Clone, Debug)]
struct Card {
    card_num: u8,
    card_suit: Suits,
}



    fn match_card(&self, deck: &[Option<Card>]) -> bool {
        for i in deck.iter() {
            match i.unwrap() {
                self => {
                    println!("\nFound card in deck!\nCard found is {:#?}\n", i.unwrap());
                    return true;
                }
                _ => continue,
            }
        }
        false
    }

我明白了:

`self` value is a keyword and may not be bound to variables or shadowed

【问题讨论】:

  • 很难回答您的问题,因为它不包含minimal reproducible example。我们无法分辨代码中存在哪些 crate(及其版本)、类型、特征、字段等。如果您尝试在Rust Playground 上重现您的错误,如果可能的话,这将使我们更容易为您提供帮助,否则在全新的 Cargo 项目中,然后在edit 您的问题中包含附加信息。您可以使用Rust-specific MRE tips 来减少您在此处发布的原始代码。谢谢!

标签: rust


【解决方案1】:

match 语句将提供的值与模式相匹配。将值与模式匹配不同于测试相等性。如果后者是您想要做的,请改用if 语句。您可以在subsection on pattern syntax in the book 中阅读模式。

仅由标识符组成的模式,比如x,匹配所提供的任何值,并且该值分配x。这意味着模式self 不会将该值与self 的值进行比较,而是尝试将匹配表达式的值分配给self,这是不允许的,如错误消息所述。

你的函数应该写成这样:

fn match_card(&self, deck: &[Option<Card>]) -> bool {
    deck.iter().flatten().any(|card| card == self)
}

这假定PartialEq 是为Card 类型实现的,这通常可以使用#[derive(PartialEq)] 来完成。

上面代码中的flatten() 方法将每个Option&lt;Card&gt; 视为一个嵌套迭代器。如果选项是None,则迭代Option 不会产生任何元素,否则选项中包含的单个值。这意味着deck.iter().flatten() 是一个迭代器,它为切片中的所有Some(_) 项生成&amp;Card,而所有None 项都被简单地跳过。

【讨论】:

    【解决方案2】:

    假设Card实现PartialEq,你可以使用match guard

    fn match_card(&self, deck: &[Option<Card>]) -> bool {
        for i in deck.iter() {
            match i {
                Some(c) if c == self => {
                    println!("\nFound card in deck!\nCard found is {:#?}\n", c);
                    return true;
                }
                _ => continue,
            }
        }
        false
    }
    

    playground demo

    我不知道真正的代码是什么,但如果你没有理由使用match,那么在这里简单的if 测试会更合适。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-11
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      • 2022-07-21
      • 1970-01-01
      相关资源
      最近更新 更多