Cannot get Rust enum in scope when in box

Editor's note: The code in this question applies to pre-1.0 Rust. The original enumeration import system has been changed for Rust 1.0.

It seems like it should be easy (emulating C / C ++ enums), but I can't seem to get it to work. I just want to use an enum from the box, but that doesn't seem to work no matter what I try. Am I missing something about Rust enums (can't they be used like old C / C ++ enums)?

Log / mod.rs:

pub enum Level {
    Debug,
    Normal,
}

pub struct Log {
    pub log_level: Level,
}

      

main.rs:

extern crate project;
use project::log::{Log, Level};

fn main() {
    // error: unresolved name `Normal`.
    let logger = Log { log_level: Normal };

    // unresolved name `Level::Normal`.
    let logger = Log { log_level: Level::Normal };

    // unresolved name `log::Level::Normal`.
    let logger = Log { log_level: log::Level::Normal };

    // unresolved name `project::log::Level::Normal`.
    let logger = Log { log_level: project::log::Level::Normal };
}

      

+3


source to share


1 answer


Rust 1.0

Enumeration variants are now named under the enumeration name. These two parameters work as they are:

extern crate project;

use project::log::{Level, Log};

fn main() {
    let logger = Log {
        log_level: Level::Normal,
    };

    let logger = Log {
        log_level: project::log::Level::Normal,
    };
}

      

You can also import the module:

extern crate project;

use project::log;

fn main() {
    let logger = log::Log {
        log_level: log::Level::Normal,
    };
}

      

Or you can import all the enumeration options:



extern crate project;

use project::log::{Log, Level::*};

fn main() {
    let logger = Log {
        log_level: Normal,
    };
}

      

Before Rust 1.0

You need to import each variant of the enumeration by name, not just the name of the enumeration, to use its unqualified name. Change the second line in main.rs to

use project::log::{Log, Debug, Normal};

      

Alternatively, you can use a qualified name without the Level::

path part , since the enumeration variants are not names like C ++ enum classes.

use project::log;
... Log { log_level: log::Normal };

      

+4


source







All Articles