Help using dependencies

Hi everybody,

I'm running a really simple issue, but as a complete newbie to Rust I can't seem to figure it out. I'm trying to get a very simple one-liner going to log a statement using log4rs. To do so I've got the following Cargo.toml:

[package]
name = "rustexample"
version = "0.1.0"
authors = ["me@gmail.com"]

[dependencies]
log = "0.4.17"
log4rs = "1.2.0"

Then the following content in src/main.rs:

use log::info;
use log4rs;

fn main() {
    info!("Hello, world!");
}

If I use print!("Hello, world!") it works fine. When using cargo build I get the following error:

error[E0432]: unresolved import `log4rs`
 --> src/main.rs:2:5
  |
2 | use log4rs;
  |     ^^^^^^ no `log4rs` in the root

error: cannot determine resolution for the macro `info`
 --> src/main.rs:5:5
  |
5 |     info!("Hello, world!");
  |     ^^^^
  |
  = note: import resolution is stuck, try simplifying macro imports

I can imagine the second error is a result of the first one. I'm probably missing something very obvious, but I can't find it. Can anybody throw me a lifeline? :smiley:

You don't need to use top-level crate names. If all you want is to call info!(), then use log::info() is sufficient. Or use a fully-qualified name and no explicit import: log::info!().

By the way, the redundant/useless import shouldn't lead to an error. It's just a warning by default. For example, the identical code compiles and runs in the Playground.

Does your Cargo.toml not have an edition key set? If not you're using the old 2015 edition, which requires you to add extern crate crate_name; before you can use it.

I'm not sure why you wouldn't be getting the same error for the log crate though

1 Like

thank you for the quick reply, I was under the impression the warning was preventing it from running. I managed to get it working based on your solution, thanks a lot!

there's no 'edition' field in the Cargo.toml, this is the only content:

[package]
name = "project"
version = "0.1.0"
authors = ["me@gmail.com"]

[dependencies]
log = "0.4.17"
log4rs = "1.2.0"

Unless you're intentionally targeting the 2015 edition, you probably want to add edition = "2021" after the authors = ... line

2 Likes

That actually made it work correctly with the import, thanks a lot! 2015 is still the default for backwards compatibility I take it?

Yup! If you use cargo new it will automatically fill in the edition in the generated Cargo.toml

1 Like

That makes sense then, I manually constructed the Cargo.toml. Thanks a lot!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.