okuryu
okuryu

Reputation: 221

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`

Upvotes: 0

Views: 426

Answers (1)

Shepmaster
Shepmaster

Reputation: 431159

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 };

Upvotes: 1

Related Questions