简体   繁体   中英

How do I store a yaml-rust enum into an instance of a struct?

I'm trying to define a struct which has the Yaml type from yaml-rust but it doesn't work. What data type should I use in the struct in this case?

extern crate yaml_rust;

use yaml_rust::{Yaml, YamlLoader};

struct Book {
    doc: Yaml,
}

fn main() {
    let s = "
foo:
    - list1
    - list2
";
    let docs = YamlLoader::load_from_str(s).unwrap();
    let doc = &docs[0];
    let _book = Book { doc: doc };
}
error[E0308]: mismatched types
  --> src/main.rs:17:29
   |
17 |     let _book = Book { doc: doc };
   |                             ^^^ expected enum `yaml_rust::Yaml`, found reference
   |
   = note: expected type `yaml_rust::Yaml`
              found type `&yaml_rust::Yaml`

Re-read the error message:

expected type `yaml_rust::Yaml`
   found type `&yaml_rust::Yaml`

You don't have an instance of Yaml ; you have a reference to an instance. Go back and review The Rust Programming Language , specifically the chapter on references and borrowing .

You can remove the value from the docs vector and pass it into your struct:

let mut docs = YamlLoader::load_from_str(s).unwrap();
let doc = docs.swap_remove(0);
let _book = Book { doc };

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