Rustの?
演算子はエラー処理を簡略化できて便利ですが、main
関数内では使えませんでした。
use std::fs::File;
use std::io::prelude::*;
fn main() {
let mut file = File::create("foo.txt")?;
file.write_all(b"Hello, world!")?;
}
これはエラーになるわけです:
error[E0277]: the `?` operator can only be used in a function that returns `Result` (or another type that implements `std::ops::Try`)
--> src/main.rs:15:20
|
15 | let mut file = File::create("foo.txt")?;
| ^^^^^^^^^^^^^^^^^^^^^^^^ 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`
なるほど、?
演算子は戻り値がResult
(あるいはstd::ops::Try
を実装している型)を返す場合にしか使えないと。
ところで[来るRust 1.25のissue][1_25]を見ているとこんなものがありました:
[1_25]: https://github.com/rust-lang/rust/milestone/44
Stabilize main
with non-() return types #48453
https://github.com/rust-lang/rust/issues/48453
これは正にやりたかったやつですね(*'▽')
早速やってみましょう。#![feature(termination_trait)]
で有効にするようです:
# ![feature(termination_trait)]
use std::error::Error;
use std::result::Result;
use std::fs::File;
use std::io::prelude::*;
fn main() -> Result<(), Box<Error>> {
let mut file = File::create("foo.txt")?;
file.write_all(b"Hello, world!")?;
Ok(())
}
安定化して1.25に入ると良いですね(/・ω・)/