Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you import and reference enum types in Rust?

Tags:

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.

like image 985
quux00 Avatar asked Jan 24 '14 03:01

quux00


1 Answers

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

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;
}
like image 119
Sergey Zalizko Avatar answered Oct 12 '22 09:10

Sergey Zalizko