LoginSignup
15
7

More than 5 years have passed since last update.

main関数で?演算子を使う

Posted at

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を見ているとこんなものがありました:

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に入ると良いですね(/・ω・)/

15
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
7