Martin Cowie
Martin Cowie

Reputation: 2601

Compiler says: the trait bound `Foo: serde::de::Deserialize` is not satisfied - when it is

I endeavour to save my struct to user preferences. My code follows

use serde::{Serialize, Deserialize};
use preferences::AppInfo;

const APP_INFO: AppInfo = AppInfo{name: "some-name", author: "some-author"};
#[derive(Serialize, Deserialize, PartialEq, Debug)]
pub struct Foo {
    bar: i32
}

fn main() {
    let x = Foo{bar: 12};

    // Attempt 1: cannot find a `save` function
    // x.save(x, &APP_INFO, "foo/bar").unwrap();

    // Attempt 2: Foo leaves Serialize & Deserialise unsatisfied
    preferences::Preferences::save(&x, &APP_INFO, "foo/bar").unwrap();

}

Despite this line #[derive(Serialize, Deserialize, PartialEq, Debug)] the compiler grumbles ..

error[E0277]: the trait bound `Foo: serde::ser::Serialize` is not satisfied
   --> src/main.rs:17:5
    |
17  |     preferences::Preferences::save(&x, &APP_INFO, "foo/bar").unwrap();
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `serde::ser::Serialize` is not implemented for `Foo`
    | 
   ::: /Users/martincowie/.cargo/registry/src/github.com-1ecc6299db9ec823/preferences-1.1.0/src/lib.rs:302:16
    |
302 |     fn save<S: AsRef<str>>(&self, app: &AppInfo, key: S) -> Result<(), PreferencesError>;
    |                ---------- required by this bound in `save`
    |
    = note: required because of the requirements on the impl of `Preferences` for `Foo`

The unsatisfied trait bound <S: AsRef<str>> relates to the parameter key, which is a string literal.

This is more or less inspired by the example at https://docs.rs/preferences/1.1.0/preferences/

What need I do to placate the compiler?

Upvotes: 2

Views: 2788

Answers (1)

Sebastian Redl
Sebastian Redl

Reputation: 71979

Check your cargo.lock. Most likely, your main application is pulling in a different version of serde than the preferences crate.

It appears that preferences depends on serde-0.9, but chances are you're pulling in serde-1.0. This means that your struct implements serde-1.0::Deserialize, but preferences wants serde-0.9::Deserialize.

The inability of the compiler to produce a nice message for this case is a long-standing bug.

Upvotes: 3

Related Questions