Using serde-json in lib.rs

Hey everyone :hugs:

I have main.rs and lib.rs in the same folder,
what should I do to use serve-json functionality in lib.rs?

I ask this questions because i see only examples for main.rs :disappointed_relieved:

There's nothing special here, you do the same thing.

Have you tried it? If you have a specific error we can help!

1 Like

from my lib.rs:

extern crate serde;
extern crate serde_json;
#[macro_use] extern crate serde_derive;

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: u8,
    phones: Vec<String>,
}

I get this error:

an extern crate loading macros must be at the crate root

and if i move these crates to main.rs,
then Serialize and Deserialize can't be found:

cannot find derive macro Deserialize in this scope

From the point of view of your main.rs, the lib.rs is an external crate not a module. That means to depend on lib.rs from main.rs you need extern crate the_crate_name not mod lib.

1 Like

Show us:

  • Cargo.toml
  • main.rs. The first 20 or so lines will do.

Cargo.toml:

[package]
name = "rust"
version = "0.1.0"
authors = ["TomBash"]

[dependencies]
serde = "1"
serde_json = "1"
serde_derive = "1"

[[bin]]
name = "rust"
path = "main.rs"

[lib]
name = "rust"
path = "lib.rs"

main.rs:

mod lib;
use std::io::prelude::*;
use std::fs::File;

extern crate serde;
extern crate serde_json;
#[macro_use] extern crate serde_derive;

fn main() {
}

In that case I'm pretty sure you should find @dtolnay hit the nail exactly on the head then. (I wish I had his clairvoyance!).

1 Like