Не могу закодировать структуру в JSON в Rust

Я следую руководству по веб-фреймворку Iron, которое казалось довольно простым, но я не могу кодировать структуру как JSON.

extern crate iron;
extern crate rustc_serialize;

use iron::prelude::*;
use iron::status;
use rustc_serialize::json;

struct Greeting {
    msg: String,
}

fn main() {
    fn hello_world(_: &mut Request) -> IronResult<Response> {
        let greeting = Greeting { msg: "hello_world".to_string() };
        let payload = json::encode(&greeting).unwrap();
        // Ok(Response::with((status::Ok,payload)))
    }

    // Iron::new(hello_world).http("localhost:3000").unwrap();
}

Мой Cargo.toml

[package]
name = "iron_init"
version = "0.1.0"
authors = ["mazbaig"]

[dependencies]
iron = "*"
rustc-serialize = "*"

И моя ошибка:

error: the trait bound `Greeting: rustc_serialize::Encodable` is not satisfied [E0277]
        let payload = json::encode(&greeting).unwrap();
                      ^~~~~~~~~~~~
help: run `rustc --explain E0277` to see a detailed explanation
note: required by `rustc_serialize::json::encode`

Я вроде понимаю, что правильные типы не попадают в json.encode() функционировать, но мне трудно понять, чего он хочет от меня. Я, наверное, упускаю что-то действительно простое.

1 ответ

Решение

Вы не предоставили само учебное пособие, которое используете, но похоже, что оно совпадает с этим от brson.

extern crate iron;
extern crate rustc_serialize;

use iron::prelude::*;
use iron::status;
use rustc_serialize::json;

#[derive(RustcEncodable)]
struct Greeting {
    msg: String
}

fn main() {
    fn hello_world(_: &mut Request) -> IronResult<Response> {
        let greeting = Greeting { msg: "Hello, World".to_string() };
        let payload = json::encode(&greeting).unwrap();
        Ok(Response::with((status::Ok, payload)))
    }

    Iron::new(hello_world).http("localhost:3000").unwrap();
    println!("On 3000");
}

Заметили что-нибудь другое между ними?

#[derive(RustcEncodable)]
struct Greeting {
    msg: String
}

Вы должны указать, что Encodable Черта реализована. В этом случае вы можете сделать это, выведя RustcEncodable,

Другие вопросы по тегам