Unable to use rust crates - rust

I'm new to rust. I'm following a getting started tutorial that imports the crate random-number but when running the code I'm getting the error can't find crate for 'random_number'. What am I doing wrong?
~/Cargo.toml:
[package]
name = "test"
version = "0.0.1"
edition = "2021"
[dependencies]
random-number = "0.1.8"
~/src/main.rs:
extern crate random_number;
use random_number::random;
fn main() {
let num: i8 = random!(..);
println!("{}", num);
}

rustc is not meant to be used directly. It is the compiler that can compile a .rs file, but it doesn't have any dependency manager attached to it. So if you decide to use rustc directly, you need to manage your dependencies manually.
cargo is the official tool to compile Rust projects. It internally uses rustc, but additionally manages the project's dependencies that are specified in Cargo.toml.
cargo build --release && ./target/release/<project_name>
or the short form:
cargo run --release

Related

"unresolved import thiserror" when expanding the code with "rustc -Zunpretty=expanded"

My Cargo.toml
[package]
name = "rust"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
thiserror = { version = "1.0.30", default-features = false }
My rustc --version
rustc 1.59.0-nightly (cfa3fe5af 2021-12-31)
My package structure
src/
error.rs
lib.rs
main.rs
My lib.rs
pub mod error;
My error.rs
use thiserror::Error;
#[derive(Error, Debug)]
pub enum DataStoreError {
#[error("the data for key `{0}` is not available")]
Redaction(String),
#[error("invalid header (expected {expected:?}, found {found:?})")]
InvalidHeader { expected: String, found: String },
#[error("unknown data store error")]
Unknown,
}
I am trying to expand the error.rs to understand what #[derive(Error, Debug)] does to the code. However, running
rustc -Zunpretty=expanded src/error.rs
results in 5 errors, the first of which is unresolved import thiserror, which makes me think I need to change how I invoke the compiler, perhaps with a full module path to error?
rustc does not know about the crates in Cargo.toml. It does not know about this file at all. It's Cargo that uses it, and passes things as flags to rustc.
Don't do this work manually. It'll require replicating all of the work Cargo does.
Instead, Cargo has a command for running rustc commands: cargo rustc. You pass the arguments to rustc after the --:
cargo rustc -- -Zunpretty=expanded
However, there is not a flag to filter the results. Passing a filename to rustc just causes it to consider this file as the entry point, and it will not work with Cargo since it passes its own file as the entry point: lib.rs or main.rs.
However, as stated in the comment from #Cerberus, it's preferred to use cargo expand. Note that it does not take a filename but a path, so to expand error it will look like:
cargo expand error
And to expand DataStoreError:
cargo expand error::DataStoreError

Missing crate when using rustc but not using cargo

I'm using the epub crate on version 1.2.3 and my Cargo.toml is formatted as such
[package]
name = "cl-epub-reader"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
epub = "1.2.22"
and my main.rs is
use epub::doc::EpubDoc;
use epub::doc::NavPoint;
use std::env::args;
fn main() {
let args: Vec<String> = args().collect();
let doc = EpubDoc::new(&args[1]).unwrap();
// assert!(doc.is_ok());
println!("{:?}", doc.mdata("title"));
}
All it does is get the uses the path from the a user input then it gets the title metadata and printing it.
When I run cargo run it outputs an error about an error about going out of range, which is expected however when I run rustc src/main.rs the error is error[E0433]: failed to resolve: maybe a missing crate `epub`?
Does anyone know the cause of this and how to solve this issue?
When you call rustc directly, you need to pass the appropriate options to tell the compiler where the crates are installed on your computer. cargo handles that automatically for you (you can use the -v option to cargo build to see the actual rustc command lines it uses).

can't find crate when using extern command

I am learning rust, now I tried to use Diesel to do some operation to database. I write the main.rs like this:
#[macro_use]
extern crate reddwarf_music;
fn main(){
}
then compile the project using command cargo build, shows error like this:
~/Documents/GitHub/reddwarf_music on  develop! ⌚ 14:50:50
$ cargo build ‹ruby-2.7.2›
Compiling reddwarf_music v0.1.0 (/Users/dolphin/Documents/GitHub/reddwarf_music)
error[E0463]: can't find crate for `reddwarf_music`
--> src/main.rs:3:1
|
3 | extern crate reddwarf_music;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ can't find crate
error: aborting due to previous error
For more information about this error, try `rustc --explain E0463`.
error: could not compile `reddwarf_music`
To learn more, run the command again with --verbose.
(base)
and this is my Cargo.toml:
[package]
name = "reddwarf_music"
version = "0.1.0"
edition = "2018"
[dependencies]
rocket = { version = "0.5.0-rc.1", features = ["json"] }
rand = "0.8.4"
serde = { version = "1.0.64", features = ["derive"] }
serde_json = "1.0.64"
reqwest = "0.11.4"
# database
diesel = { version = "1.4.4", features = ["postgres"] }
dotenv = "0.15.0"
am I doing the right way? the next step I want to use the mod like this:
use reddwarf_music::schema::posts::dsl::*;
I am follow the docs step by step from here to using diesel. what should I do to make it work as expect? the diesel official docs use it like this way. In my project, it did not work.
As far as I can see, the crate you are trying to compile is called reddwarf_music. extern crate tries to include a crate into the crate you're currently compiling. You're in effect trying to include the crate reddwarf_music into itself in order to use proc_macros from reddwarf_music in reddwarf_music. This is unfortunately not possible.
What the official Diesel documentation does is slightly different. Their library crate is called diesel_demo, but the code run when running cargo run --bin is actually the code inside the folder bin, which is not directly a part of the library crate, and instead part of a separate binary crate. If you instead of the file main.rs in the root, create a file inside a bin folder and run cargo build --bin, I think it should work.
(This has been edited to more directly answer the question)

Unable to find crate that is listed in [build-dependencies] section

I try to compile my project with the command cargo build.
build.rs
extern crate csv;
use std::path::Path;
use std::fs::OpenOptions;
use std::io::BufWriter;
use std::io::Write;
#[allow(non_snake_case)]
fn processCSV(filename: &str, sourcePath: &str, enumName: &str) {
println!("Generate rust source code from schema {}",filename);
let mut ret: Vec<String> = Vec::new();
let mut rdr = csv::Reader::from_file(filename).unwrap().flexible(true);
for record in rdr.records().map(|r| r.unwrap()) {
}
let path = Path::new(sourcePath);
let file = match OpenOptions::new().write(true).create(true).open(&path) {
Ok(file) => file,
Err(..) => panic!("Cannot create file {}",path.display()),
};
let mut writer = BufWriter::new(file);
writer.write_all(b"test\n");
}
fn main() {
processCSV("../schemas/Test.csv", "./src/mod/common/StatusCode.rs", "StatusCode");
}
and Cargo.toml
[package]
name = "rust-test"
version = "0.0.1"
build = "build.rs"
[lib]
path = "src/lib.rs"
[dependencies]
[build-dependencies]
csv = "*"
I can see this error :
src/lib.rs:1:1: 1:18 error: can't find crate for csv
src/lib.rs:1 extern crate csv;
but when I change flexible(true) to flexible(false) it compiles just fine without any errors. What do I need to do to fix this?
I am using Rust 1.2.0 on Windows 7 64-bit.
Changing flexible(false) for flexible(true) makes no difference for me; both fail. The problem is that you've chosen build-dependencies for some reason, instead of just dependencies.
Using the src/lib.rs file that you provided in your answer, and this Cargo.toml file:
[package]
name = "stack-overflow"
version = "0.1.0"
authors = ["A. Developer <a.developer#example.com>"]
[dependencies]
csv = "*"
It compiles fine.
If you need to access a dependency both in your build.rs and in your project, you need to include the dependency in both sections.
A build dependency is a dependency for a build script, which is a helper binary compiled and run before your main crate is built (designed to be used for code-generation, and building/finding native C libraries, etc.).
Normal dependencies used by the main code should just fall into the "dependencies" section, e.g.
[dependencies]
csv = "0.14"
There's also a "dev-dependencies" section, which are dependencies that are only needed for testing, i.e. they are compiled and used only for cargo test. This allows crates to depend on, for example, quickcheck for running tests without contaminating the main artifact.
In summary, running cargo build will do something like:
build any build-dependencies
build the build script (pointing the compiler to the built build-dependencies), and run it
build any dependencies
build the main crate (pointing the compiler to the built dependencies)
Running cargo test adds:
build any dev-dependencies
build the main crate with --test to create a test runner for any in-source #[test]s (pointing the compiler to both the dependencies and dev-dependencies)
build any external examples or tests, also pointing to both the dependencies and dev-dependencies

"entry point could not be located" when running program on Windows

I wrote a program to parse some filenames in Rust using the standard Regex crate. The program runs fine on Linux, but when I tried to compile and run it on Windows, I get some kind of DLL error. I don't really understand what is going on with this, but it's all I have to go on.
This is the compiler version that I'm using:
F:\Coding\rust-shutterstock-deduper\target (master)
λ rustc --version
rustc 1.0.0-nightly (3ef8ff1f8 2015-02-12 00:38:24 +0000)
This is the program that I'm trying to run:
#![feature(plugin)]
#![plugin(regex_macros)]
extern crate regex_macros;
extern crate regex;
fn main() {
let x = regex!(".*");
}
And my Cargo.toml file:
[package]
name = "my_package"
version = "0.0.1"
authors = ["Nate Mara <natemara#gmail.com>"]
[dependencies]
regex = "0.1.14"
regex_macros = "0.1.8"
Are there compiler flags that I should be passing in, or do I need to run this in a special way, or... what am I doing wrong here? I'm just running with cargo run
Add #[no_link] to your code:
#![plugin(regex_macros)]
#[no_link]
extern crate regex_macros;
Right now, plugins are crates, which means they get linked in. The regex_macros crate should tell you to add no_link, but this is a temporary workaround for a Rust issue. However, it looks like this is in the process of being fixed.

Resources