在模式匹配时修改字段 [英] modifying a field while pattern matching on it

查看:65
本文介绍了在模式匹配时修改字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我第一次在Rust上进行了尝试(编写了XML标记器),自然无法理解所有内容:

I tried my hands at Rust for the first time today (writing a XML tokenizer), and naturally don’t understand everything:

我有一个结构体,其字段可以采用枚举值:

I have a struct with field that can take an enum value:

enum State { Outside, InATag(~str) }
struct Tokenizer { state: State }

impl Tokenizer中,我想匹配当前状态,并在某些情况下进行更改,但这总是会出现use of moved value错误.

In a impl Tokenizer, I want to match on the current state, and change it in some cases, however this always gives a use of moved value error.

H访问和/或声明状态字段,以便我可以在其上进行匹配并在match分支内更改其值?

H to access and/or declare the state field so that I can match on it and change its value inside a match branch?

抱歉,我要更改标记生成器的状态字段,而不是状态的字符串字段!

Sorry for the confusion, I meant to change the Tokenizer’s state field, not the state’s String field!

match self.state {
    InATag(name) => self.state = Outside,
    Outside => ()
}

推荐答案

好的,随着问题的澄清,这是我的修改答案:

Okay, with the clarified variant of the question, here is my revised answer:

enum State { Outside, InATag(~str) }
struct Tokenizer { state: State }

impl Tokenizer {
    fn toggle(&mut self) {
        match self {
            &Tokenizer { state: InATag(*) } => { self.state = Outside }
            &Tokenizer { state: Outside }   => { self.state = InATag(~"baz") }
        }
    }
}

fn main() {
    let mut t1 = Tokenizer { state: InATag(~"foo") };
    match t1 {
        Tokenizer { state: InATag(*) } => { t1.state = Outside }
        Tokenizer { state: Outside } => { /* impossible */ }
    }
    io::println(fmt!("Hello t1: %?", t1));
    let mut t2 = Tokenizer { state: InATag(~"bar") };
    t2.toggle();
    io::println(fmt!("World t2: %?", t2));
}

我承认,我实际上并没有想到它会像上面那样容易,而且我可以轻易相信,对上述代码进行小的更改可能会导致它开始无法借用检查.但是,如果没有问询者提供的更详尽的示例,很难说出上面的代码是否适合他的目的.

I admit, I actually did not expect it to be as easy as the above, and I can easily believe that small changes to the above code could cause it to start failing to borrow-check. But without a more fleshed out example from the asker, it is hard to tell whether the above code would suit his purposes or not.

哦,这是我编译并运行代码时的输出:

Oh, here's the output when I compile and run the code:

% rustc /tmp/m.rs
warning: no debug symbols in executable (-arch x86_64)
% /tmp/m
Hello t1: {state: Outside}
World t2: {state: Outside}
% 

这篇关于在模式匹配时修改字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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