はじめに
RustでGetした情報を得るプログラムを書いていたのですが、reqwestの公式の通りに書いてもエラーになってしまいました。
Rustは始めたばかりで良くわからないのですが、とりあえずメモとして残しておきます。
環境
Rustの場合、何を残しておけば良いか分からないので、とりあえず必要そうな情報をのせておきます。
$ cargo -V
cargo 1.34.0 (6789d8a0a 2019-04-01)
$ rustc --version
rustc 1.34.1 (fc50f328b 2019-04-24)
$ rustup --version
rustup 1.18.3 (435397f48 2019-05-22)
まずはエラーとなるケース
公式のサンプルを元に書くとこんな感じで取れそうな気がしますが、これだとエラーになります。
main.rs
extern crate reqwest;
fn main() {
let res = reqwest::get("https://www.google.co.jp/")?.text();
println!("{:?}", res);
}
$ cargo run
Compiling hello v0.1.0 (/Users/tasogarei/rust/hello)
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
--> src/main.rs:4:15
|
4 | let res = reqwest::get("https://www.google.co.jp/")?.text();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
|
= help: the trait `std::ops::Try` is not implemented for `()`
= note: required by `std::ops::Try::from_error`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
error: Could not compile `hello`.
To learn more, run the command again with --verbose.
いや、Result<Response>
で返ってくるねんけど!と言いたくなりますが、なぜかエラーになります。
エラーがでないように修正
とりあえずの解決法
main.rs
extern crate reqwest;
fn main() {
let res = reqwest::get("https://www.google.co.jp/").unwrap().text();
println!("{:?}", res);
}
Result
ではあるので、とりあえずとしてunwrap()
すれば取り出せます。
ただし、Result
はエラーが返却される可能性がある型なので、本来はmatch
するなりなんなりしてきちんとエラーについても判定させるべきではあります。
今回は自分用として作成しているので、気にしないこととします。