如何在rust中从内部函数返回外部函数中的变量

jyztefdp  于 2022-12-19  发布在  其他
关注(0)|答案(1)|浏览(188)

我正在使用rust-macios板条箱,我有这个简单的函数。

fn request_contact_permission() -> bool {
    let store = CNContactStore::m_new();

    store.request_access_for_entity_type_completion_handler(
        CNEntityType::Contacts,
        |granted: bool, _error: NSError| {
            if granted {
                println!("Access granted");
            } else {
                println!("Access denied");
            }
        },
    );

}

如何让request_contact_permission返回granted的值?request_access_for_entity_type_completion_handler触发一个对话框,并在用户与对话框交互时返回一个值。

toe95027

toe950271#

在不知道store.request_access_for_entity_type_completion_handler的确切类型的情况下,我不能肯定地说,但是假设它接受FnMutFnOnce,您可以让它捕获一个可变的外部变量,然后返回该外部变量。

let mut granted_result: bool = false;
store.request_access_for_entity_type_completion_handler(
    CNEntityType::Contacts,
    |granted: bool, _error: NSError| {
        granted_result = granted; // Capturing a variable from the outer scope
        if granted {
            println!("Access granted");
        } else {
            println!("Access denied");
        }
    },
);
granted_result

相关问题