[go: up one dir, main page]

const_fn 0.3.0

An attribute for easy generation of a const function with conditional compilations.
Documentation

#[const_fn]

crates-badge docs-badge license-badge rustc-badge

An attribute for easy generation of a const function with conditional compilations.

Usage

Add this to your Cargo.toml:

[dependencies]
const_fn = "0.3"

The current const_fn requires Rust 1.31 or later.

Examples

When using like the following functions to control unstable features:

[features]
const_unstable = []

It can be written as follows:

#![cfg_attr(feature = "const_unstable", feature(const_fn))]
use const_fn::const_fn;

pub struct Foo<T> {
    x:T,
}

impl<T: Iterator> Foo<T> {
    /// Constructs a new `Foo`.
    #[const_fn(feature = "const_unstable")]
    pub const fn new(x: T) -> Self {
        Self { x }
    }
}

Code like this will be generated:

#![cfg_attr(feature = "const_unstable", feature(const_fn))]

pub struct Foo<T> {
    x:T,
}

impl<T: Iterator> Foo<T> {
    /// Constructs a new `Foo`.
    #[cfg(feature = "const_unstable")]
    pub const fn new(x: T) -> Self {
        Self { x }
    }

    /// Constructs a new `Foo`.
    #[cfg(not(feature = "const_unstable"))]
    pub fn new(x: T) -> Self {
        Self { x }
    }
}

See test_suite for more examples.

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.