Confused by Compilation Prompt in `serde-test` Project

When I construct a project for testing the serde crate in Window11 vscode:

# Cargo.toml
[package]
name = "serde-test"
version = "0.1.0"
edition = "2024"
[dependencies]
serde = { version = "1.0.219", features = ["derive"] }
serde-json ="1.0.140"
// main.rs
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

fn main() {
    let kv = BTreeMap::from([("a", 3)]);
    let sj = serde_json::to_string(&kv).unwrap();
    let kv: BTreeMap<&str, i32> = serde_json::from_str(&sj).unwrap();
    println!("{kv:?}");
}

When compiling, the output is as follows:

PS D:\dev\rust-app\util> cargo -V
cargo 1.85.0 (d73d2caf9 2024-12-31)

PS D:\dev\rust-app\util> cargo build -p serde_test
    Updating `rsproxy-sparse` index
error: no matching package found
searched package name: `serde-json`
perhaps you meant:      serde_json
location searched: `rsproxy-sparse` index (which is replacing registry `crates-io`)

required by package `serde-test v0.1.0 (D:\dev\rust-app\util\serde_test)`

As shown above:

  1. There is an error: no matching package found.
  2. It suggests perhaps you meant: serde_json. How does it deduce this? I am confused.

So, how can I resolve this issue? Restarting VS Code does not work.

Besides, here is an important note:
Before this, I created a local project named serde_json , which showed some prompts about conflicts between the local serde_json and the existing serde_json on crates.io. After that, I removed it. I do not know whether this has something to do with it.

Thanks.

You need to use serde_json here. The package is called serde_json, not serde-json: crates.io: Rust Package Registry

3 Likes

It checks the registry for similar names, and found that while serde-json does not exist, serde_json does.

3 Likes

Thanks to bjorn3 and kpreid, your suggestions worked.

However, when I try to add a property to my custom type KV, I encounter another error:

#[derive(Debug, Deserialize, Serialize)]
struct KV(BTreeMap<&'static str, i32>);

The error message is:

lifetime may not live long enough
requires that `'de` must outlive `'static`

But it works fine when I use BTreeMap directly as shown in the code above:

let kv: BTreeMap<&str, i32> = BTreeMap::from([("a", 3)]);

Serde can't create new &'static strs from deserialization. Use String instead.

2 Likes

Following the clue you provided, I rechecked the declaration of the Deserialize trait. Turns out, the parameter str needs a 'de lifetime, which should outlive the 'static lifetime of the object type. The following code demonstrates this successfully.

#[derive(Debug, Deserialize)]
struct Str(&'static str);
let s = serde_json::from_str::<Str>(r#""123""#).unwrap();
println!("{:?}", s);

Thanks for all your replies.