如何基于枚举存储和访问impl?

时间:2018-03-28 16:06:26

标签: rust

我有以下基于枚举的impl。我不知道我应该如何存储并从中获取我的值。

这里是impl:

pub enum Baz {
    // My data structure has a string and a number
    Foo(String),
    Bar(u64),
}

impl Baz {
    pub fn get(baz: Baz) -> String {
        let mut result = "".to_string();
        match baz {
            Baz::Foo(v) => {},
            Baz::Bar(v) => { result = v.to_string() },
        }
        result
    }
    pub fn new() {
        // Do I even need new() for instance creation?!
        println!("Hello World");
    }
}

以下是我如何访问它:

mod bazbazbaz;
use bazbazbaz::baz;

fn main() {
    let x: data::Baz;
    x::Foo("mystring".to_string());
    x::Bar(42);
    x.get(Baz::Bar); // I expect "42" here as string
}

这只是一个语法错误,还是我一般误解了这个概念?

2 个答案:

答案 0 :(得分:3)

我认为你将struct的概念与enum的概念混淆。

以某种方式构造 struct 你的数据,而枚举存在 enum 作为结构数据结构的选择。

struct Baz {
    foo: String,
    bar: u64
}

这包含String a u64

enum Baz {
    Foo(String),
    Bar(u64),
}

这包含String a u64

答案 1 :(得分:1)

  

这只是一个语法错误,还是我一般误解了这个概念?

你总体上误解了这个概念。扣上......

pub enum Baz {  
    // My data structure has a string and a number  
    Foo(String),
    Bar(u64),
}

您的数据结构没有字符串和数字。您的数据结构为Baz::Foo,在这种情况下,它包含StringBaz::Bar,在这种情况下,它包含u64

您正在寻找的不是enum,而是struct

pub struct Baz {
    foo: String,
    bar: u64,
}

与enum不同,此结构包含一个字符串一个数字。

这是一般差异的说明,即枚举列出了不同的"变体",其中的实例可以是一个且只有一个。在您的定义中,FooBar变体

另一方面,

Structs定义了一个字段列表,所有必须存在于实例中。如果您需要更详细的说明,请参阅my answer to this questionthis comment中建议的@Shepmaster,请查看 The Rust Programming Language

fn main() {
    let x: data::Baz;
    x::Foo("mystring".to_string());
    x::Bar(42);
    x.get(Baz::Bar); // I expect "42" here as string
}

再次,我可以看到你正在尝试做什么。目的是创建Baz的实例,将其存储在x中,将字符串设置为"mystring",并将数字设置为42。但是,由于Baz是一个枚举,您实际所做的是创建两个单独的Baz实例:

fn main() {
    // This creates a `Baz::Foo` containing a string, and stores it
    // in `foo`.
    let foo = Baz::Foo("mystring".to_string());

    // This creates a `Baz::Bar` containing a number, and stores it
    // in `bar`.
    let bar = Baz::Bar(42);

    // You can get the value out in a number of ways. This is one:
    match foo {
        Baz::Foo(string) => println!("{}", string), // prints "mystring"
        Baz::Bar(number) => println!("{}", number),
    }

    match bar {
        Baz::Foo(string) => println!("{}", string),
        Baz::Bar(number) => println!("{}", number), // prints "42"
    }
}

使用Baz作为struct的定义,您想要做的是:

fn main() {
    let qux = Baz {
        foo: "mystring".to_string(),
        bar: 42,
    };

    // Get the value of `foo` and print it.
    println!("{}", qux.foo); // prints "mystring"

    // Get the value of `bar` and print it.
    println!("{}", qux.bar); // prints "42"
}