简体   繁体   中英

How do you import and reference enum types in Rust?

How do you import and reference enum types from the Rust std lib?

I'm trying to use the Ordering enum from the std::sync::atomics module. My attempts so far have all ended in failure:

use std::sync::atomics::AtomicBool;
use std::sync::atomics::Ordering;

// error unresolved import: there is no `Relaxed` in `std::sync::atomics::Ordering`
// use std::sync::atomics::Ordering::Relaxed;  

fn main() {
    let mut ab = AtomicBool::new(false);
    let val1 = ab.load(Ordering::Relaxed); // error: unresolved import:
                                           // there is no `Relaxed` in `std::sync::atomics::Ordering`
    println!("{:?}", val1);

    ab.store(true, Ordering.Relaxed);      // error: unresolved name `Ordering`
    let val2 = ab.load(Ordering(Relaxed)); // error: unresolved name `Relaxed`
    println!("{:?}", val2);    
}

I'm currently using Rust v. 0.9.

As of Rust 1.0, enum variants are scoped inside of their enum type. They can be directly use d:

pub use self::Foo::{A, B};

pub enum Foo {
    A,
    B,
}

fn main() {
    let a = A;
}

or you can use the type-qualified name:

pub enum Foo {
    A,
    B,
}

fn main() {
    let a = Foo::A;
}

Editor's note: This answer predates Rust 1.0 and is not applicable for Rust 1.0.

Enum variants are not scoped inside the enum; they are thus std::sync::atomics::Relaxed , &c.

Scoped enum variants is the subject of issue 10090 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM