我在Rust中包装libxml2作为学习Rust FFI的练习,我遇到了一些奇怪的事情.我是Rust的新手,但我相信以下内容应该有效.
在main.rs我有:
mod xml;
fn main() {
if let doc = xml::parse_file("filename") {
doc.simple_function();
}
}
Run Code Online (Sandbox Code Playgroud)
并且xml.rs是:
extern create libc;
use libc::{c_void, c_char, c_int, c_ushort};
use std::ffi::CString;
// There are other struct definitions I've implemented that xmlDoc
// depends on, but I'm not going to list them because I believe
// they're irrelevant
#[allow(non_snake_case)]
#[allow(non_camel_case_types)]
#[repr(C)]
struct xmlDoc {
// xmlDoc structure defined by the libxml2 API
}
pub struct Doc {
ptr: *mut xmlDoc
}
impl Doc {
pub fn simple_function(&self) {
if self.ptr.is_null() {
println!("ptr doesn't point to anything");
} else {
println!("ptr is not null");
}
}
}
#[allow(non_snake_case)]
#[link(name = "xml2")]
extern {
fn xmlParseFile(filename: *const c_char) -> *mut xmlDoc;
}
pub fn parse_file(filename: &str) -> Option<Doc> {
unsafe {
let result;
match CString::new(filename) {
Ok(f) => { result = xmlParseFile(f.as_ptr()); },
Err(_) => { return None; }
}
if result.is_null() {
return None;
}
Some(Doc { ptr: result })
}
}
Run Code Online (Sandbox Code Playgroud)
我将C结构包装xmlDoc在一个很好的Rust友好结构中Doc,以便在安全(Rust)和不安全(C)数据类型和函数之间进行清晰的描述.
这一切都适用于大多数情况,除了我编译时,我在main.rs中得到一个错误:
src/main.rs:38:13: 38:28 error: no method named 'simple_function' found
for type 'std::option::Option<xml::Doc>' in the current scope
src/main.rs:38 doc.simple_function();
^~~~~~~~~~~~~~~
error: aborting due to previous error`
Run Code Online (Sandbox Code Playgroud)
它似乎确信doc是Option<xml::Doc>,即使我使用的if let应该拆开包装形式Option类型.有什么我做错了吗?
match xml::parse_file("filename") {
Some(doc) => doc.simple_function(),
None => {}
}
Run Code Online (Sandbox Code Playgroud)
以上工作正常,但if let如果我能够,我想使用Rust 的功能.
你需要通过实际的模式if let(不同于像雨燕,其特殊的情况下语言if let的Option类型):
if let Some(doc) = xml::parse_file("filename") {
doc.simple_function();
}
Run Code Online (Sandbox Code Playgroud)