Unresolved import for certain tokio features - rust

I am trying to use tokios background event loop feature, but I am unable to use any tokio reactor features and I have no idea why. I created a new project with cargo new tokio-test --bin and copy-pasted the code snippet and in the link for establishing a basic TCP connection.
Cargo.toml
[package]
name = "tokio-test"
version = "0.1.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tokio = { version = "1.11.0", features = ["full"] }
main.rs
use tokio::prelude::*;
use tokio::net::TcpStream;
fn main() {
let addr = "93.184.216.34:9243".parse().unwrap();
let connect_future = TcpStream::connect(&addr);
let task = connect_future
.and_then(|socket| {
println!("successfully connected");
Ok(())
})
.map_err(|e| println!("failed to connect; err={:?}", e));
tokio::run(task);
}
When running cargo build I get:
error[E0432]: unresolved import `tokio::prelude`
--> src/main.rs:1:12
|
1 | use tokio::prelude::*;
| ^^^^^^^ could not find `prelude` in `tokio`
error[E0425]: cannot find function `run` in crate `tokio`
--> src/main.rs:16:12
|
16 | tokio::run(task);
| ^^^ not found in `tokio`
error[E0599]: no method named `and_then` found for opaque type `impl Future` in the current scope
--> src/main.rs:10:10
|
10 | .and_then(|socket| {
| ^^^^^^^^ method not found in `impl Future`
|
help: consider `await`ing on the `Future` and calling the method on its `Output`
|
10 | .await.and_then(|socket| {
| ^^^^^^
Clearly I am missing some directive from tokio but I cannot figure how to include it. My rustc version is rustc 1.55.0 (c8dfcfe04 2021-09-06).

You're depending on tokio v1.11.0 (the current release), but your docs are for v0.1.22. The interface has changed quite drastically, that's why you are not finding all those types, functions and modules. Current documentation is here.
If you found the documentation via Google: The problem of Google returning old docs.rs results is well known. There is an open issue that will solve this problem.
Also, docs.rs displays a warning on the top left of the page to go to the latest version if you are not on that version anyway. You should get in the habit of clicking it unless you know you're using an older version. (Thanks to kmdreko for pointing this out in the comments)

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

Rust - Suddenly Can't find split method on WebSocket?

I'm a rust newbie and I'm having a lot of trouble getting some simple ws examples to run.
I have a new project with this in the Cargo.toml file:
[package]
name = "ouranos4"
version = "0.1.0"
authors = ["jasongoodwin <jay.michael.goodwin#gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tokio = { version = "1", features = ["full"] }
warp = "0.3"
And then I have the warp ws example found here: https://github.com/seanmonstar/warp/blob/master/examples/websockets.rs
// use futures::{FutureExt, StreamExt};
use warp::Filter;
#[tokio::main]
async fn main() {
let routes = warp::path("echo")
// The `ws()` filter will prepare the Websocket handshake.
.and(warp::ws())
.map(|ws: warp::ws::Ws| {
// And then our closure will be called when it completes...
ws.on_upgrade(|websocket| {
// Just echo all messages back...
let (tx, rx) = websocket.split();
rx.forward(tx).map(|result| {
if let Err(e) = result {
eprintln!("websocket error: {:?}", e);
}
})
})
});
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}
And I swear this was compiling but out of the blue I'm getting these errors:
Compiling ouranos4 v0.1.0 (/Users/jasongoodwin/Development/src/ouranos4)
error[E0599]: no method named `split` found for struct `WebSocket` in the current scope
--> src/main.rs:13:42
|
13 | let (tx, rx) = websocket.split();
| ^^^^^ method not found in `WebSocket`
|
::: /Users/jasongoodwin/.cargo/registry/src/github.com-1ecc6299db9ec823/futures-util-0.3.14/src/stream/stream/mod.rs:1359:8
|
1359 | fn split<Item>(self) -> (SplitSink<Self, Item>, SplitStream<Self>)
| ----- the method is available for `Box<WebSocket>` here
|
= 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:
|
2 | use futures_util::stream::stream::StreamExt;
|
error: aborting due to previous error
For more information about this error, try `rustc --explain E0599`.
error: could not compile `ouranos4`
I've recreated the project, cleaned the project, done everything imaginable. Switched the rust compiler version to nightly and back.
I'm really confused as to why I can't split this now. I've tried different examples, different crates, and I keep seeing this error.
I'm tempted to throw my laptop away and try on a different computer :P
I needed to add some more imports!
Thanks to kmdreko.
use futures::StreamExt;
use futures::FutureExt;

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

How do I use std::collections::BitSet in stable Rust?

I am trying to use BitSet data structure, but it gives me a compile error saying it was not able to find the BitSet. Has std::collections::BitSet been released in the stable version?
use std::collections::BitSet;
fn main() {
println!("Hello, world!");
}
Produces the error:
error[E0432]: unresolved import `std::collections::BitSet`
--> src/main.rs:1:5
|
1 | use std::collections::BitSet;
| ^^^^^^^^^^^^^^^^^^^^^^^^ no `BitSet` in `collections`
It seems that BitSet existed in Rust 1.3.0, which is very old, but was already deprecated at that time and finally removed by this commit.
Instead, you can use bit-set crate, as suggested by the deprecation message above. There's also documentation.
extern crate bit_set;
use bit_set::BitSet;
fn main() {
let mut s = BitSet::new();
s.insert(32);
s.insert(37);
s.insert(3);
println!("s = {:?}", s);
}
You'll have to add a dependency to the bit-set crate in some way. It's easy if you're using Cargo:
[package]
name = "foo"
version = "0.1.0"
authors = ["Foo Bar <foo#example.com>"]
[dependencies]
bit-set = "0.4.0" # Add this line
If you're using the official Rust Playground, you can automatically use bit-set, because it is one of the top 100 downloaded crates or a dependency of one of them.

Resources