在 Rust 中“组合”枚举的正确方法

rtv*_*iii 2 rust

我希望能够有一个总和类型,它是两个枚举成员之一,但不确定我是否正确执行此操作。这个想法是 forToken是aCoordinateAA并且 forprocess_line返回一个 s 数组Token。非常基本。但是我是否必须将Token(...)每个CoordinateAA我初始化的对象都包裹起来?

struct Coordinate {
    x: f64,
    y: f64,
    z: f64
}

enum AminoAcid {
    VAL, GLN ,ARG,
    LEU, THR ,TYR,
    SER, PRO ,CYS,
    GLY, ALA ,MET
}

enum Token {
    Coordinate(Coordinate),
    AminoAcid(AminoAcid)
}

// Want a function that returns a list of legal tokens given a &line.
fn _process_line(line:&str)->Vec<Token>{
    let token = Token::AminoAcid(AminoAcid::ARG);
    return vec![token];
}
Run Code Online (Sandbox Code Playgroud)

例如,在打字稿中我可以这样做

type A = "Fur" | "Silver" | "Glass"
type B = "Leather" | "Wood"  | "Bronze"
type Material  = A | B;

var x: Material = "Wood" // is okay
Run Code Online (Sandbox Code Playgroud)

而在这里我必须做所有Material("Wood")类型的事情

let token = Token::AminoAcid(AminoAcid::ARG);
let token = AminoAcid::ARG; // it would have been great to just have this, is this possible?
Run Code Online (Sandbox Code Playgroud)

Net*_*ave 6

您可以From为每个内部类型实现。通过实现它,您可以调用Into::into内部类型实例来获取外部枚举表示:

struct Coordinate{
    x:f64,    y:f64,    z:f64
}

enum AminoAcid {
    VAL, GLN ,ARG,
    LEU, THR ,TYR,
    SER, PRO ,CYS,
    GLY, ALA ,MET
}

enum Token {
    Coordinate(Coordinate),
    AminoAcid(AminoAcid)
}

impl From<Coordinate> for Token {
    fn from(coord: Coordinate) -> Self {
        Self::Coordinate(coord)
    }
}

impl From<AminoAcid> for Token {
    fn from(aminoacid: AminoAcid) -> Self {
        Self::AminoAcid(aminoacid)
    }
}

// Want a function that returns a list of legal tokens given a &line.
fn _process_line(line:&str)->Vec<Token>{
    return vec![AminoAcid::ARG.into()];
}
Run Code Online (Sandbox Code Playgroud)

操场