Clap says `cargo` feature flag is required - what does it mean? - rust

Here is my code in src/bin/foo.rs:
use clap::command;
pub fn main() {
let matches = command!("foo")
.about("Simple util")
.get_matches();
}
I'm getting:
error: `cargo` feature flag is required
--> src/bin/foo.rs:30:19
|
30 | let matches = command!("foo")
| ^^^^^^^^^^^^^^^
|

In your Cargo.toml file change your clap dependency to enable the cargo feature.
e.g.
clap = { version = "3.2.20", features = ["cargo"] }

Related

oneshot::channel `tokio::sync::oneshot::Receiver<()>` is not an iterator add `use futures_util::FutureExt`

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.

Why is Rocket's `Json` type not found in the `content` module?

Today I found that a project that previously worked no longer compiles. Here is a minimal example that reproduces my sudden error:
use rocket::{get, launch, routes};
use rocket::response::content;
#[get("/health")]
pub fn health() -> content::Json<String> {
content::Json("ok".parse().unwrap())
}
#[launch]
async fn rocket() -> _ {
rocket::build().mount("/actuator", routes![health])
}
error[E0412]: cannot find type `Json` in module `content`
--> src\main.rs:5:29
|
5 | pub fn health() -> content::Json<String> {
| ^^^^ not found in `content`
|
help: consider importing this struct
|
1 | use rocket::serde::json::Json;
|
error[E0425]: cannot find function, tuple struct or tuple variant `Json` in module `content`
--> src\main.rs:6:14
|
6 | content::Json("ok".parse().unwrap())
| ^^^^ not found in `content`
|
help: consider importing this tuple struct
|
1 | use rocket::serde::json::Json;
|
I am using cargo 1.59.0 (49d8809dc 2022-02-10) and rustc 1.59.0 (9d1b2106e 2022-02-23). And here are my dependencies:
[dependencies]
rocket = { version = "0.5.0-rc.1", features = ["json"] }
The content::Json is supposed to come from Rocket and should be enabled by the cargo feature above. It definitely worked the past. What should I do to fix this problem? How did this happen?
The content module was changed between Rocket release candidates. Compare the documentation for 0.5.0-rc.1 and 0.5.0-rc.2. The Json type moved to rocket::serde::json::Json. So your code should look like this:
use rocket::serde::json::Json;
pub fn health() -> Json<String> {
Json("ok".parse().unwrap())
}
But I did not upgrade the rocket version, I am still using 0.5.0-rc.1
It seems you did, albiet unknowningly. This can happen if cargo update was ran or you simply didn't preserve your Cargo.lock file (or something recreated it). It is somewhat dubious if rc.1 should be seen as compatible with rc.2, but regardless, you can lock your dependency to a specific version by prefixing it with = if you want to stay on rc.1:
[dependencies]
rocket = { version = "=0.5.0-rc.1", features = ["json"] }

How do I use hashbrown data types with Rayon parallel iterators?

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"] }

Why is 'futures::prelude::*; undecleared

For some reason it is telling me that it is undeclared when i am trying to follow an example for an IRC in rust and it makes no sense that it is not working cause i have used libraries like this before and it worked before so idk what is happening \
code:
use futures::prelude::*;
use irc::client::prelude::*;
#[tokio::main]
async fn main() -> irc::error::Result<()> {
let config = Config {
nickname: Some("pickles".to_owned()),
server: Some("chat.freenode.net".to_owned()),
channels: vec!["#rust-spam".to_owned()],
..Default::default()
};
let mut client = Client::from_config(config).await?;
client.identify()?;
let mut stream = client.stream()?;
let sender = client.sender();
while let Some(message) = stream.next().await.transpose()? {
print!("{}", message);
match message.command {
Command::PRIVMSG(ref target, ref msg) => {
if msg.contains(client.current_nickname()) {
sender.send_privmsg(target, "Hi!")?;
}
}
_ => (),
}
}
Ok(())
}
Errors
--> src\main.rs:1:5
|
1 | use futures::prelude::*;
| ^^^^^^^ use of undeclared type or module `futures`
error[E0308]: mismatched types
--> src\main.rs:9:19
|
9 | channels: vec!["#rust-spam".to_owned()],
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| expected enum `std::option::Option`, found struct `std::vec::Vec`
| help: try using a variant of the expected enum: `Some(<[_]>::into_vec(box [$($x),+]))`
|
= note: expected enum `std::option::Option<std::vec::Vec<_>>`
found struct `std::vec::Vec<_>`
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0599]: no function or associated item named `from_config` found for trait object `dyn irc::client::Client` in the current scope
--> src\main.rs:13:30
|
13 | let mut client = Client::from_config(config).await?;
| ^^^^^^^^^^^ function or associated item not found in `dyn irc::client::Client`
Cargo.toml
[package]
name = "irc"
version = "0.1.0"
authors = ["sudo"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
irc = "0.13"
tokio = { version = "0.2.22", features = ["full"] }
Edit: Added Cargo.toml
You will need to add the futures crate to your cargo file. E.g. from the docs
[dependencies]
futures = "0.3"
You need to add futures to your Cargo.toml, even though a dependency already depends on it.

Rust reqwest example json code does not compile

The example for dynamic json with reqwest
extern crate reqwest;
extern crate tokio;
extern crate serde_json; // added to after upgrade to 1.39.0
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
let echo_json: serde_json::Value = reqwest::Client::new()
.post("https://jsonplaceholder.typicode.com/posts")
.json(&serde_json::json!({
"title": "Reqwest.rs",
"body": "https://docs.rs/reqwest",
"userId": 1
}))
.send()
.await?
.json()
.await?;
println!("{:#?}", echo_json);
// Object(
// {
// "body": String(
// "https://docs.rs/reqwest"
// ),
// "id": Number(
// 101
// ),
// "title": String(
// "Reqwest.rs"
// ),
// "userId": Number(
// 1
// )
// }
// )
Ok(())
}
failed to compile for rustc 1.38.0 with reqwest = "0.9.22" and tokio = "0.2.2":
Compiling pin-project-lite v0.1.1
error: `core::slice::<impl [T]>::len` is not yet stable as a const fn
--> /Users/mick/.cargo/registry/src/github.com-1ecc6299db9ec823/bytes-0.5.2/src/bytes.rs:121:18
|
121 | len: bytes.len(),
| ^^^^^^^^^^^
error: aborting due to previous error
error: Could not compile `bytes`.
This was fixed by upgrading as of the comment by Ömer below, but now the next problems are
error[E0433]: failed to resolve: could not find `main` in `tokio`
--> main.rs:5:10
|
5 | #[tokio::main]
| ^^^^ could not find `main` in `tokio`
error[E0277]: the trait bound `std::result::Result<reqwest::Response, reqwest::Error>: std::future::Future` is not satisfied
--> main.rs:7:40
|
7 | let echo_json: serde_json::Value = reqwest::Client::new()
| ________________________________________^
8 | | .post("https://jsonplaceholder.typicode.com/posts")
9 | | .json(&serde_json::json!({
10 | | "title": "Reqwest.rs",
... |
14 | | .send()
15 | | .await?
| |______________^ the trait `std::future::Future` is not implemented for `std::result::Result<reqwest::Response, reqwest::Error>`
error[E0277]: `main` has invalid return type `impl std::future::Future`
--> main.rs:6:20
|
6 | async fn main() -> Result<(), reqwest::Error> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ `main` can only return types that implement `std::process::Termination`
|
= help: consider using `()`, or a `Result`
error: aborting due to 3 previous errors
Some errors have detailed explanations: E0277, E0433.
For more information about an error, try `rustc --explain E0277`.
error: could not compile `webtrekk`.
To learn more, run the command again with --verbose.
and the next reqwest = "0.10.0-alpha.2" tokio = { version = "0.2.2", features = ["macros"] } serde_json = "1.0.44"
➜ rust git:(master) ✗ cargo run
Updating crates.io index
error: failed to select a version for `tokio`.
... required by package `reqwest v0.10.0-alpha.2`
... which is depended on by `webtrekk v0.1.0 (/Users/mick/repo/webtrekk-client/rust)`
versions that meet the requirements `= 0.2.0-alpha.6` are: 0.2.0-alpha.6
all possible versions conflict with previously selected packages.
previously selected package `tokio v0.2.2`
... which is depended on by `webtrekk v0.1.0 (/Users/mick/repo/webtrekk-client/rust)`
failed to select a version for `tokio` which could resolve this conflict
How can these be fixed?
Your example comes from https://github.com/seanmonstar/reqwest/blob/master/examples/json_dynamic.rs and works with the following Cargo.toml, using Rust 1.39:
[package]
name = "reqwest-json_dynamic-example"
version = "0.1.0"
authors = ["fyaa"]
edition = "2018"
[dependencies]
tokio = { version = "=0.2.0-alpha.6", features = ["io", "tcp", "timer"] }
reqwest = { version = "0.10.0-alpha.2", features = ["json"] }
serde_json = "1.0.44"

Resources