我创建了以下 Rust 结构:
struct HTTPRequestHeader {
name: ~str,
data: ~str,
next: Option<~HTTPRequestHeader>
}
和下面的代码来打印它:
fn print_headers(hdr: &HTTPRequestHeader) {
println(fmt!("%s: %s", (*hdr).name, (*hdr).data));
match (*hdr).next {
Some(next_hdr) => { print_headers(next_hdr); }
None => { }
}
}
尝试编译此代码,我收到以下错误:
> rustc http_parse.rs
http_parse.rs:37:7: 37:18 error: moving out of immutable field
http_parse.rs:37 match (*hdr).next {
^~~~~~~~~~~
error: aborting due to previous error
这是什么意思?包含的行(*hdr).name, (*hdr).data)
编译没有错误。该match
声明不应该试图以hdr.next
任何方式改变,所以我看不出不变性是如何进入它的。我试图编写一个不带指针的修改版本:
fn print_headers(hdr: HTTPRequestHeader) {
println(fmt!("%s: %s", hdr.name, hdr.data));
match hdr.next {
Some(next_hdr) => { print_headers(*next_hdr); }
None => { }
}
}
这个给了我:
> rustc http_parse.rs
http_parse.rs:37:7: 37:15 error: moving out of immutable field
http_parse.rs:37 match hdr.next {
^~~~~~~~
http_parse.rs:38:36: 38:45 error: moving out of dereference of immutable ~ pointer
http_parse.rs:38 Some(next_hdr) => { print_headers(*next_hdr); }
^~~~~~~~~
error: aborting due to 2 previous errors
请帮助我了解这里发生了什么!:)