I am creating a project in Rust and just wanted to add a command line parser using clap.
However, my project fails to build:
args.rs
use clap::Parser;
/// Simple program to greet a person
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
pub struct Args {
/// Optional name to operate on
#[clap(short, long, value_parser)]
width: usize,
/// Sets a custom config file
#[clap(short, long, value_parser)]
height: usize,
/// Turn debugging information on
#[clap(short, long, value_parser)]
mines: u8,
}
Cargo.toml:
[package]
name = "rustymines"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "*"
grid = { git = "https://github.com/conqp/grid.git", branch = "main" }
clap = { version = "3.2.22", features = ["derive"] }
Error:
$ cargo build
Compiling libc v0.2.133
Compiling version_check v0.9.4
Compiling proc-macro2 v1.0.44
Compiling unicode-ident v1.0.4
Compiling quote v1.0.21
Compiling syn v1.0.101
Compiling cfg-if v1.0.0
Compiling autocfg v1.1.0
Compiling ppv-lite86 v0.2.16
Compiling heck v0.4.0
Compiling os_str_bytes v6.3.0
Compiling hashbrown v0.12.3
Compiling termcolor v1.1.3
Compiling once_cell v1.15.0
Compiling strsim v0.10.0
Compiling bitflags v1.3.2
Compiling textwrap v0.15.1
Compiling grid v0.1.0 (https://github.com/conqp/grid.git?branch=main#227750b9)
Compiling proc-macro-error-attr v1.0.4
Compiling proc-macro-error v1.0.4
Compiling clap_lex v0.2.4
Compiling indexmap v1.9.1
Compiling getrandom v0.2.7
Compiling atty v0.2.14
Compiling rand_core v0.6.4
Compiling rand_chacha v0.3.1
Compiling rand v0.8.5
Compiling clap_derive v3.2.18
Compiling clap v3.2.22
Compiling rustymines v0.1.0 (/home/rne/Projekte/rustymines)
error[E0616]: field `width` of struct `args::Args` is private
--> src/game.rs:26:24
|
26 | Self::new(args.width, args.height, args.mines)
| ^^^^^ private field
error[E0616]: field `height` of struct `args::Args` is private
--> src/game.rs:26:36
|
26 | Self::new(args.width, args.height, args.mines)
| ^^^^^^ private field
error[E0616]: field `mines` of struct `args::Args` is private
--> src/game.rs:26:49
|
26 | Self::new(args.width, args.height, args.mines)
| ^^^^^ private field
error[E0599]: no function or associated item named `parse` found for struct `args::Args` in the current scope
--> src/game.rs:30:26
|
30 | let args = Args::parse();
| ^^^^^ function or associated item not found in `args::Args`
|
::: src/game/args.rs:6:1
|
6 | pub struct Args {
| --------------- function or associated item `parse` not found for this
|
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
1 | use clap::Parser;
|
Some errors have detailed explanations: E0599, E0616.
For more information about an error, try `rustc --explain E0599`.
error: could not compile `rustymines` due to 4 previous errors
Note that none of the errors should happen, since, according to the linked clap cookbook, clap should work some magic and make the fields publicly accessible as well as implement the parse() function.
What's the issue here?
PS:
$ rustup show
Default host: x86_64-unknown-linux-gnu
rustup home: /home/rne/.rustup
stable-x86_64-unknown-linux-gnu (default)
rustc 1.63.0 (4b91a6ea7 2022-08-08)
Related
In the tokio tests I see they use oneshot::channel together with serve_with_shutdown but the the compiler tells me to add use futures_util::future::future::FutureExt but as you can see in the example below I already added that trait to the scope.
What am I missing?
Here a reprex
run cargo new tokio-test
Cargo.toml
[package]
name = "tokio-test"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tonic = "0.7"
prost = "0.10.1"
tokio = { version = "1.18", features = ["macros", "rt-multi-thread"] }
[build-dependencies]
tonic-build = "0.7.2"
src/main.rs
pub mod console {
tonic::include_proto!("console");
}
use console::console_server::{Console, ConsoleServer};
use console::{ConsoleResponse, InfoRequest};
use tokio::runtime::Runtime;
use tokio::sync::oneshot;
use tonic::{transport::Server, Request, Response};
use futures_util::FutureExt;
#[derive(Default)]
pub struct ConsoleImpl {}
#[tonic::async_trait]
impl Console for ConsoleImpl {
async fn info(
&self,
request: Request<InfoRequest>,
) -> Result<Response<ConsoleResponse>, tonic::Status> {
println!("{}", request.get_ref().text);
Ok(Response::new(ConsoleResponse {}))
}
}
fn main() {
let addr = "[::1]:50051".parse().unwrap();
let maxconsole = ConsoleImpl::default();
println!("Console server listening on {}", addr);
let mut rt = Runtime::new().expect("failed to obtain a new RunTime object");
let (shutdown_send, shutdown_recv) = oneshot::channel::<()>();
let server_future = Server::builder()
.add_service(ConsoleServer::new(maxconsole))
// .serve(addr)
.serve_with_incoming_shutdown(
addr,
shutdown_recv.map(drop),
);
rt.block_on(server_future).expect("failed to successfully run the future on RunTime");
}
src/console.proto
syntax = "proto3";
package console;
service Console {
rpc info (InfoRequest) returns (ConsoleResponse) {}
}
message InfoRequest {
string text = 1;
}
message ConsoleResponse {
}
If you build the project it will complain
❯ cargo build
Updating crates.io index
Compiling tokio-test v0.1.0 (C:\s\tokio-test)
error[E0432]: unresolved import `futures_util`
--> src\main.rs:10:5
|
10 | use futures_util::FutureExt;
| ^^^^^^^^^^^^ use of undeclared crate or module `futures_util`
error[E0599]: `tokio::sync::oneshot::Receiver<()>` is not an iterator
--> src\main.rs:40:27
|
40 | shutdown_recv.map(drop),
| ^^^ `tokio::sync::oneshot::Receiver<()>` is not an iterator
|
::: C:\Users\FrancescElies\.cargo\registry\src\github.com-1ecc6299db9ec823\tokio-1.20.1\src\sync\oneshot.rs:318:1
|
318 | pub struct Receiver<T> {
| ---------------------- doesn't satisfy `tokio::sync::oneshot::Receiver<()>: Iterator`
|
= note: the following trait bounds were not satisfied:
`tokio::sync::oneshot::Receiver<()>: Iterator`
which is required by `&mut tokio::sync::oneshot::Receiver<()>: Iterator`
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
1 | use futures_util::future::future::FutureExt;
|
Some errors have detailed explanations: E0432, E0599.
For more information about an error, try `rustc --explain E0432`.
error: could not compile `tokio-test` due to 2 previous errors
Yes, you added the FutureExt import, but did not tell Rust where to find that crate. The critical part of the error message is:
error[E0432]: unresolved import `futures_util`
--> src\main.rs:10:5
|
10 | use futures_util::FutureExt;
| ^^^^^^^^^^^^ use of undeclared crate or module `futures_util`
This can be fixed by adding the futures_util crate to your Cargo.toml dependency section.
I'm trying to follow this tutorial on Windows with
D:\src\rust\hecto>cargo --version
cargo 1.57.0 (b2e52d7ca 2021-10-21)
D:\src\rust\hecto>rustc --version
rustc 1.57.0 (f1edd0429 2021-11-29)
I'm having following code in 2 project directories:
use std::io;
use std::io::Read;
fn die(e: std::io::Error) {
panic!(e);
}
fn main() {
let ctrl_q = 'q' as u8 & 0b1_1111;
for b in io::stdin().bytes() {
match b {
Ok(b) => {
let c = b as char;
if c.is_control() {
println!("{:#b} \r", b);
}
else {
println!("{:?} ({})\r", b, c);
}
if b == ctrl_q {
break;
}
},
Err(err) => die(err),
}
}
}
After deleting target and Cargo.lock, in one project I'm getting following output:
C:\temp\hecto-tutorial-die-on-input-error>cargo build
Updating crates.io index
Compiling winapi v0.3.9
Compiling cfg-if v1.0.0
Compiling parking_lot_core v0.8.5
Compiling smallvec v1.7.0
Compiling scopeguard v1.1.0
Compiling bitflags v1.3.2
Compiling instant v0.1.12
Compiling lock_api v0.4.5
Compiling crossterm_winapi v0.9.0
Compiling parking_lot v0.11.2
Compiling crossterm v0.22.1
Compiling hecto v0.1.0 (C:\temp\hecto-tutorial-die-on-input-error)
warning: panic message is not a string literal
--> src\main.rs:5:12
|
5 | panic!(e);
| ^
|
= note: `#[warn(non_fmt_panics)]` on by default
= note: this usage of panic!() is deprecated; it will be a hard error in Rust 2021
= note: for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2021/panic-macro-consistency.html>
help: add a "{}" format string to Display the message
|
5 | panic!("{}", e);
| +++++
help: or use std::panic::panic_any instead
|
5 | std::panic::panic_any(e);
| ~~~~~~~~~~~~~~~~~~~~~
warning: `hecto` (bin "hecto") generated 1 warning
Finished dev [unoptimized + debuginfo] target(s) in 13.22s
while in the other I'm getting
D:\src\rust\hecto>cargo build
Updating crates.io index
Compiling winapi v0.3.9
Compiling parking_lot_core v0.8.5
Compiling cfg-if v1.0.0
Compiling scopeguard v1.1.0
Compiling smallvec v1.7.0
Compiling bitflags v1.3.2
Compiling instant v0.1.12
Compiling lock_api v0.4.5
Compiling crossterm_winapi v0.9.0
Compiling parking_lot v0.11.2
Compiling crossterm v0.22.1
Compiling hecto v0.1.0 (D:\src\rust\hecto)
error: format argument must be a string literal
--> src\main.rs:5:12
|
5 | panic!(e);
| ^
|
help: you might be missing a string literal to format with
|
5 | panic!("{}", e);
| +++++
error: could not compile `hecto` due to previous error
Any idea why it compiles fine in one but fails in the other project?
The behaviour of the panic! macro changed a bit with the Rust 2021 edition, to make it more consistent with other format family macros. An entire chapter of the migration guide is dedicated to this.
The fix, and the link with the detailed information is also indicated in the error message you get:
= note: `#[warn(non_fmt_panics)]` on by default
= note: this usage of panic!() is deprecated; it will be a hard error in Rust 2021
= note: for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2021/panic-macro-consistency.html>
help: add a "{}" format string to Display the message
|
5 | panic!("{}", e);
| +++++
help: or use std::panic::panic_any instead
|
5 | std::panic::panic_any(e);
| ~~~~~~~~~~~~~~~~~~~~~
I have set up a rust base project according to the Getting Started page of the rocket-framework:
I added this line to my Cargo.toml: rocket = "0.4.10"
My main.rs:
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}
fn main() {
rocket::ignite().mount("/", routes![index]).launch();
}
When I try to run (or cargo build it) I get the following error:
Compiling rocket v0.4.10 error[E0277]: the trait bound `(dyn handler::Handler + 'static): handler::Handler` is not satisfied --> /Users/.../.cargo/registry/src/github.com-1ecc6299db9ec823/rocket-0.4.10/src/rocket.rs:299:41
| 299 | let outcome = route.handler.handle(request, data);
| ^^^^^^ the trait `handler::Handler` is not implemented for `(dyn handler::Handler + 'static)`
For more information about this error, try `rustc --explain E0277`. error: could not compile `rocket` due to previous error
I also tried it with previous versions of the rocket framework, all of them threw the same error.
Of course I'm using the latest nightly version of rust, right before cargo build I entered following commands:
rustup override set nightly
info: using existing install for 'nightly-x86_64-apple-darwin'
info: override toolchain for '/Users/...' set to 'nightly-x86_64-apple-darwin'
nightly-x86_64-apple-darwin unchanged - rustc 1.58.0-nightly (bd41e09da 2021-10-18)
Is there a known issue with the latest rust compiler on MacOS? Is there any other solution I could try?
I have a hashbrown::HashSet, and I am trying to use Rayon's par_iter with it, but I cannot figure out the right syntax.
Cargo.toml
[package]
name = "basic"
version = "0.1.0"
authors = ["Me <me#example.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
hashbrown = "0.9.1"
rayon = "1.5.0"
src/main.rs
use hashbrown::*;
use rayon::prelude::*;
// use hashbrown::hash_set::rayon::*;
fn main() {
println!("Hello, world!");
let hs = HashSet::new();
for n in 1..100 {
hs.insert(n);
}
hs.par_iter().for_each(|n| println!("n={}", n));
}
This fails to compile.
error[E0599]: no method named `par_iter` found for struct `hashbrown::HashSet<{integer}>` in the current scope
--> src/main.rs:13:8
|
13 | hs.par_iter().for_each(|n| println!("n={}", n));
| ^^^^^^^^ method not found in `hashbrown::HashSet<{integer}>`
|
::: /Users/me/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.9.1/src/set.rs:114:1
|
114 | pub struct HashSet<T, S = DefaultHashBuilder> {
| --------------------------------------------- doesn't satisfy `_: rayon::iter::IntoParallelRefIterator`
|
= note: the method `par_iter` exists but the following trait bounds were not satisfied:
`&hashbrown::HashSet<{integer}>: IntoParallelIterator`
which is required by `hashbrown::HashSet<{integer}>: rayon::iter::IntoParallelRefIterator`
warning: unused import: `rayon::prelude`
--> src/main.rs:2:5
|
2 | use rayon::prelude::*;
| ^^^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
The hashset-rayon docs suggest that hashbrown::hash_set::rayon has a Rayon-related data type, and I know that sometimes I need to use traits to make functionality available. However, if I uncomment the import, it cannot even find the module:
error[E0432]: unresolved import `hashbrown::hash_set::rayon`
--> src/main.rs:3:26
|
3 | use hashbrown::hash_set::rayon::*;
| ^^^^^ could not find `rayon` in `hash_set`
I am running Rust 1.49.0 on a Mac:
$ rustup show
Default host: x86_64-apple-darwin
rustup home: /Users/tda0106/.rustup
installed toolchains
--------------------
stable-x86_64-apple-darwin (default)
nightly-x86_64-apple-darwin
active toolchain
----------------
stable-x86_64-apple-darwin (default)
rustc 1.49.0 (e1884a8e3 2020-12-29)
What is the problem?
Edit
As #E_net4 the curator pointed out in the comments, the rayon support is in a feature. Changing the dependencies to
[dependencies]
hashbrown = { version = "0.9.1", features = ["rayon"] }
rayon = "1.5.0"
makes this work, without needing the extra use statement.
It's not clear to me where the documentation indicates this.
If you look inside of the hashbrown crate, you will see that rayon support is only present if the rayon feature is enabled. You can enable the feature in your Cargo.toml:
[dependencies]
hashbrown = { version = "0.9.1", features = ["rayon"] }
I have a strange dependency problem. Here are steps to reproduce:
❯ rustc -V
rustc 1.35.0-nightly (82e2f3ec2 2019-03-20)
❯ git clone https://github.com/google/tarpc.git
❯ cd tarpc/example-service
❯ cargo build
Finished dev [unoptimized + debuginfo] target(s) in 0.13s
❯ git rev-parse HEAD
06544faa5a0872d4be989451afc0a2b1e1278df4
Now I replace a line in Cargo.toml from
bincode-transport = { package = "tarpc-bincode-transport", version = "0.3", path = "../bincode-transport" }
to
bincode-transport = { package = "tarpc-bincode-transport", git="https://github.com/google/tarpc.git", rev="06544faa5a0872d4be989451afc0a2b1e1278df4" }
which represents the same codebase (I think version = 0.3 is meaningless),
Then I have a build error
❯ cargo build
Blocking waiting for file lock on the git checkouts
Updating git repository `https://github.com/google/tarpc.git`
Compiling tarpc-example-service v0.2.0 (tarpc/example-service)
error[E0277]: the trait bound `tarpc_bincode_transport::Transport<tokio_tcp::stream::TcpStream, _, _>: tarpc_lib::transport::Transport` is not satisfied
--> example-service/src/server.rs:45:4
|
45 | .incoming(transport)
| ^^^^^^^^ the trait `tarpc_lib::transport::Transport` is not implemented for `tarpc_bincode_transport::Transport<tokio_tcp::stream::TcpStream, _, _>`
error[E0277]: the trait bound `tarpc_bincode_transport::Transport<tokio_tcp::stream::TcpStream, _, _>: tarpc_lib::transport::Transport` is not satisfied
--> example-service/src/client.rs:20:29
|
20 | let mut client = await!(service::new_stub(client::Config::default(), transport))?;
| ^^^^^^^^^^^^^^^^^ the trait `tarpc_lib::transport::Transport` is not implemented for `tarpc_bincode_transport::Transport<tokio_tcp::stream::TcpStream, _, _>`
|
= note: required by `service::new_stub`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
error: Could not compile `tarpc-example-service`.
warning: build failed, waiting for other jobs to finish...
error[E0599]: no method named `respond_with` found for type `impl futures_core::stream::Stream` in the current scope
--> example-service/src/server.rs:48:4
|
48 | .respond_with(service::serve(HelloServer));
| ^^^^^^^^^^^^
|
= note: the method `respond_with` exists but the following trait bounds were not satisfied:
`&impl futures_core::stream::Stream : tarpc_lib::server::Handler<_, _, _>`
`&mut impl futures_core::stream::Stream : tarpc_lib::server::Handler<_, _, _>`
`impl futures_core::stream::Stream : tarpc_lib::server::Handler<_, _, _>`
error: aborting due to 2 previous errors
Some errors occurred: E0277, E0599.
For more information about an error, try `rustc --explain E0277`.
error: Could not compile `tarpc-example-service`.
cargo clean didn't help. How is this possible?
This is the same problem as Why is a trait not implemented for a type that clearly has it implemented? — by pulling in both the git version of the code and the local version of the code (via tarpc = { path = "../tarpc" }), you are compiling the tarpc crate two different times. The traits from each are not the same as each other, they are effectively different versions of the same crate.
This can be verified using cargo tree -d -i:
tarpc-lib v0.2.0 (https://github.com/google/tarpc.git?rev=06544faa5a0872d4be989451afc0a2b1e1278df4#06544faa)
└── tarpc-bincode-transport v0.3.0 (https://github.com/google/tarpc.git?rev=06544faa5a0872d4be989451afc0a2b1e1278df4#06544faa)
└── tarpc-example-service v0.2.0 (/private/tmp/tarpc/example-service)
tarpc-lib v0.2.0 (/private/tmp/tarpc/rpc)
└── tarpc v0.14.1 (/private/tmp/tarpc/tarpc)
└── tarpc-example-service v0.2.0 (/private/tmp/tarpc/example-service)
tarpc-trace v0.1.0 (https://github.com/google/tarpc.git?rev=06544faa5a0872d4be989451afc0a2b1e1278df4#06544faa)
└── tarpc-lib v0.2.0 (https://github.com/google/tarpc.git?rev=06544faa5a0872d4be989451afc0a2b1e1278df4#06544faa)
└── tarpc-bincode-transport v0.3.0 (https://github.com/google/tarpc.git?rev=06544faa5a0872d4be989451afc0a2b1e1278df4#06544faa)
└── tarpc-example-service v0.2.0 (/private/tmp/tarpc/example-service)
tarpc-trace v0.1.0 (/private/tmp/tarpc/trace)
└── tarpc-lib v0.2.0 (/private/tmp/tarpc/rpc)
└── tarpc v0.14.1 (/private/tmp/tarpc/tarpc)
└── tarpc-example-service v0.2.0 (/private/tmp/tarpc/example-service)
If you consistently use the version from git, it will work:
tarpc = { git = "https://github.com/google/tarpc.git", rev = "06544faa5a0872d4be989451afc0a2b1e1278df4", features = ["serde1"] }