次の 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
ここで何が起こっているのかを理解するのを手伝ってください!:)