rust 可变变量在赋值给变量时变得不可返回

nwnhqdif  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(121)

当我尝试做selector = &mut (Value of potential selector)时,它可以工作。但是当我尝试分配给一个临时变量,然后检查它是否是Some时,它不能返回。
我试图添加一个生存期,但我只得到语法错误。

use std::option::Option;
use std::vec::Vec;

struct Node<Record> {
    pub character: char,
    pub children: Vec<Node<Record>>,
    pub record: Option<Record>
}

struct Matcher<Record> {
    root_node: Node<Record>
}

impl<Record> Matcher<Record> {
    pub fn new() -> Self {
        Self {
            root_node: Node {
                character: 'f',
                children: Vec::new(),
                record: None
            }
        }
    }

    pub fn test(&mut self) {
        let left = Node { character: 'l', children: Vec::new(), record: None };
        let right = Node { character: 'r', children: Vec::new(), record: None };

        self.root_node.children.push(left);
        self.root_node.children.push(right);
    }

    pub fn find_mutably<'a>(&mut self, path: &[char]) -> Option<&mut Node<Record>> {
        let mut selector: &mut Node<Record> = &mut self.root_node;

        for path_segment_index in 0..path.len() {
            let path_segment = path[path_segment_index];
            let potential_selector = selector
                .children
                .iter_mut()
                .find(|child| child.character == path_segment);

            // if let Some(mut new_selector) = potential_selector {
                selector = &mut potential_selector.unwrap();
            // } else {
            //     return None;
            // }
        }

        Some(selector) // Error happens here
    }
}

字符串

du7egjpx

du7egjpx1#

new_selector是一个&mut Node<Record>,它匹配selector。您可以直接分配它:

pub fn find_mutably<'a>(&mut self, path: &[char]) -> Option<&mut Node<Record>> {
    let mut selector: &mut Node<Record> = &mut self.root_node;

    for path_segment_index in 0..path.len() {
        let path_segment = path[path_segment_index];
        let potential_selector = selector
            .children
            .iter_mut()
            .find(|child| child.character == path_segment);

        if let Some(new_selector) = potential_selector {
            selector = new_selector;
        } else {
            return None;
        }
    }

    Some(selector)
}

字符串
Playground

hs1ihplo

hs1ihplo2#

这可能是一个错误的编译器错误消息-如果你在potential_selector.unwrap()前面去掉&mut,它会编译。

相关问题