-1

I've been trying to follow Rust modules confusion when there is main.rs and lib.rs but without success

My Cargo.toml

[package]
name = "wasm_jd"
version = "0.1.0"
edition = "2021"

src/lib.rs

use serde_json::json;
use serde_json::Value;
use Value::*;

pub fn preview(contracted: Vec<&str>, json: Value) -> Value {
    // contracted is read only in the rest of the code
    convert(&contracted, "", &json)
}
...

src/main.rs

use serde_json::json;
use serde_json::Value;
use wasm_jd::preview;

fn main() {
    let j: Value = json!({"a": 1});
    let tmp: Value = preview(Vec::new(), j);
    let d = tmp.to_string();
    println!("{}", d)
}

When I do cargo run I get

error[E0432]: unresolved import `wasm_jd`
 --> src/main.rs:3:5
  |
3 | use wasm_jd::preview;
  |     ^^^^^^^ use of undeclared crate or module `wasm_jd`

As far as I can see the names match up correctly so I'm very confused?

Herohtar
  • 5,347
  • 4
  • 31
  • 41
Simon H
  • 20,332
  • 14
  • 71
  • 128
  • That changes the error to `1 | use crate::preview; no 'preview' in the root`. I tried `use crate::lib::preview` with a similar error – Simon H Sep 29 '22 at 07:12
  • When I paste the code you posted into a new fresh directory, this compiles just fine (after adding dependencies and creating a stub for `convert`). Maybe there's something else wrong with it, can you paste the output of running `tree` or `exa -T`? – Caesar Sep 29 '22 at 10:31

1 Answers1

1

Your package is named wasm_jd. Typical configuration for building to WebAssembly is for Cargo.toml to have

[lib]
crate-type = ["cdylib"]

This configuration will cause the error you see, because the compiler is being instructed to build a dynamic library not usable as a Rust dependency.

If you no longer need it, remove it. If you want both builds, specify that:

[lib]
crate-type = ["lib", "cdylib"]

(The lib type is the default if no crate-type is specified.)

Once you do this, your original code,

use wasm_jd::preview;

should succeed.

Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
  • Thanks. I made that change and now have `let tmp: Value = lib::preview(Vec::new(), j); ^^^ use of undeclared crate or module 'lib'` – Simon H Sep 29 '22 at 14:35
  • 1
    @SimonH That's because the library is called `wasm_jd`, not `lib`. Your original code in the question was correct. – Kevin Reid Sep 29 '22 at 14:44