std::unreachable

Macro std::unreachable

macro_rules! unreachable {
    (  ) => { ... };
    (
$ msg : expr ) => { ... };
    (
$ fmt : expr , $ ( $ arg : tt ) * ) => { ... };
}

A utility macro for indicating unreachable code.

This is useful any time that the compiler can't determine that some code is unreachable. For example:

  • Match arms with guard conditions.
  • Loops that dynamically terminate.
  • Iterators that dynamically terminate.

Panics

This will always panic.

Examples

Match arms:

fn foo(x: Option<i32>) {
    match x {
        Some(n) if n >= 0 => println!("Some(Non-negative)"),
        Some(n) if n <  0 => println!("Some(Negative)"),
        Some(_)           => unreachable!(), // compile error if commented out
        None              => println!("None")
    }
}

Iterators:

fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
    for i in 0.. {
        if 3*i < i { panic!("u32 overflow"); }
        if x < 3*i { return i-1; }
    }
    unreachable!();
}

© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/macro.unreachable.html

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部