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.
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 create an MQTT connection with tokio and the codec provided in the mqtt_v5 crate. My code does not compile, and I don't understand why. Here is what I have written so far, the send code might not be correct.
use tokio::net::TcpStream;
use tokio_util::codec::Framed;
use tokio_util::codec::Decoder;
use std::net::SocketAddrV4;
use mqtt_v5::types::Packet as MqttPacket;
use mqtt_v5::codec::MqttCodec;
use futures_sink::Sink;
use futures_core::stream::Stream;
struct MqttConn {
inner: Framed<TcpStream, MqttCodec>,
}
impl MqttConn {
async fn new(addr: SocketAddrV4) -> MqttConn {
let tcp = TcpStream::connect(addr).await.expect("cannot connect to mqtt");
MqttConn { inner: MqttCodec::new().framed(tcp) }
}
async fn handle(&self, handler: &dyn Fn(&MqttConn, MqttPacket) -> ()) {
while let Some(p) = self.inner.next().await {
handler(self, p)
}
}
async fn send(&self, p: MqttPacket) {
self.inner.start_send(p);
}
}
I get these errors from the compiler:
error[E0599]: no method named `framed` found for struct `MqttCodec` in the current scope
--> src/mqtt.rs:17:44
|
17 | MqttConn { inner: MqttCodec::new().framed(tcp) }
| ^^^^^^ method not found in `MqttCodec`
|
= help: items from traits can only be used if the trait is in scope
= note: the following trait is implemented but not in scope; perhaps add a `use` for it:
`use tokio_util::codec::decoder::Decoder;`
error[E0599]: no method named `next` found for struct `Framed<tokio::net::TcpStream, MqttCodec>` in the current scope
--> src/mqtt.rs:21:40
|
21 | while let Some(p) = self.inner.next().await {
| ^^^^ method not found in `Framed<tokio::net::TcpStream, MqttCodec>`
error[E0599]: no method named `start_send` found for struct `Framed<tokio::net::TcpStream, MqttCodec>` in the current scope
--> src/mqtt.rs:27:20
|
27 | self.inner.start_send(p);
| ^^^^^^^^^^ method not found in `Framed<tokio::net::TcpStream, MqttCodec>`
warning: unused import: `tokio_util::codec::Decoder`
--> src/mqtt.rs:3:5
|
3 | use tokio_util::codec::Decoder;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused import: `futures_sink::Sink`
--> src/mqtt.rs:7:5
|
7 | use futures_sink::Sink;
| ^^^^^^^^^^^^^^^^^^
The compiler says that the Decoder trait is not in scope, but I use it. If I try the suggested import I find that the module tokio_util::codec::decoder is private. Based on the source tokio_util::codec::decoder::Decoder is reexported as tokio_util::codec::Decoder. Also if I read the docs correctly, Framed should implement Sink and Stream therefore it should have the next and start_send methods.
Relevant lines from Cargo.toml:
[dependencies]
tokio = { version = "1.0.1", features = ["full"] }
tokio-util = { version = "0.6", features = ["full"] }
futures-sink = "0.3.9"
futures-core = "0.3.9"
mqtt-v5 = "0.1.1"
How can I get this to compile?
You have a number of library incompatibilities that are causing some less-than-obvious error messages.
mqtt-v5 depends on tokio-util^0.3, which was written for tokio 0.2, not 1.0. You'll need to roll back to tokio 0.2 and tokio-util 0.3. This should fix the problem with Decoder and Sink.
Additionally, the Stream trait only provides poll_next(), which is the task-level stream method. next() is provided by the StreamExt trait, along with other convenience methods similar to those found in Iterator.
I'm new to rust and started experimenting with actix_web and sqlx. the goal is to create a simple, open-source Blog engine, but after I implemented the CLI argument parser and basic SQL connection pool, the code doesn't compile anymore. I'm getting the following error:
error[E0308]: mismatched types
--> src/main.rs:17:1
|
17 | #[actix_web::main]
| ^^^^^^^^^^^^^^^^^^
| |
| expected enum `std::result::Result`, found `()`
| help: try using a variant of the expected enum: `Ok(#[actix_web::main])`
18 | async fn main() -> std::io::Result<()> {
| ------------------- expected `std::result::Result<(), std::io::Error>` because of return type
|
= note: expected enum `std::result::Result<(), std::io::Error>`
found unit type `()`
= note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.
error: could not compile `rusty_read`.
To learn more, run the command again with --verbose.
the error suggests to use std::result::Result<(), std::io::Error> as return type, but I get the same error when replacing the current return type with it:
error[E0308]: mismatched types
--> src/main.rs:17:1
|
17 | #[actix_web::main]
| ^^^^^^^^^^^^^^^^^^
| |
| expected enum `std::result::Result`, found `()`
| help: try using a variant of the expected enum: `Ok(#[actix_web::main])`
18 | async fn main() -> std::result::Result<(), std::io::Error> {
| --------------------------------------- expected `std::result::Result<(), std::io::Error>` because of return type
|
= note: expected enum `std::result::Result<(), std::io::Error>`
found unit type `()`
= note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.
error: could not compile `rusty_read`.
To learn more, run the command again with --verbose.
so far I couldn't find anybody with the same issue and could not find any reason for it.
My Code:
/Cargo.toml
[package]
name = "rusty_read"
version = "0.1.0"
authors = ["LeMoonStar <webmaster#unitcore.de>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix-web = "3.0.0-beta.1"
rust-ini = "0.15"
sqlx = { version = "0.4.0-beta.1", features = [ "all-databases", "any", "tls" ] }
clap = "2"
/src/main.rs
use actix_web::{get, web, App, HttpServer, Responder};
use ini::Ini;
use sqlx::pool::Pool;
use sqlx::any;
#[get("/")]
async fn index() -> impl Responder {
format!("index")
}
#[get("/article/{id}")]
async fn article(info: web::Path<u32>) -> impl Responder {
format!("article nr.{}", info)
}
#[actix_web::main]
async fn main() -> std::result::Result<(), std::io::Error> {
let conf = Ini::load_from_file("conf.ini").unwrap_or(Ini::load_from_str("[Server]
bindAddress = \"127.0.0.1:8080\"
[Database]
url = \"mysql://user:password#localhost/blog\"
").unwrap());
let matches = clap::App::new("Rusty Read")
.version("0.1 INDEV")
.author("LeMoonStar <webmaster#unitcore.de>")
.about("a blog engine written in rust")
.subcommand(clap::SubCommand::with_name("config")
.about("sets various configurations for the blog")
.arg(clap::Arg::with_name("address")
.short("a")
.long("adress")
.help("sets the address the http server binds on (eg. 127.0.0.1:8080)")
.takes_value(true))
.arg(clap::Arg::with_name("database")
.short("d")
.long("database")
.help("sets the url to the database (eg. mysql://user:password#localhost/blog)")
.takes_value(true)))
.subcommand(clap::SubCommand::with_name("init_database")
.about("Initializes the database which is set in the conf.ini file (or with the config command)"))
.get_matches();
if let Some(matches) = matches.subcommand_matches("config") {
if matches.is_present("address") {
conf.section(Some("Server")).unwrap()
.insert("bindAddress", "127.0.0.1:8080");
}
if matches.is_present("database") {
conf.section(Some("Database")).unwrap()
.insert("url", "mysql://user:password#localhost/blog");
}
} else if let Some(matches) = matches.subcommand_matches("init_database") {
} else {
let mut section = conf.section(Some("Server")).expect("conf.ini requires a [Server] section.");
let bind_address = section.get("bindAddress").expect("conf.ini's [Server] section requires a bindAdress.");
section = conf.section(Some("Database")).expect("conf.ini requires a [Database] section.");
let db_url = section.get("url").expect("conf.ini's [Database] section requires a url.");
let pool = Pool::<any::Any>::connect(db_url).await.expect("database connection pool could not be created.");
HttpServer::new(move || {
App::new()
.service(article)
.service(index)
.data(pool.clone())
})
.bind(bind_address).expect("could not bind http server")
.run()
.await;
}
}
I hope someone can help me with this problem since I can't continue to work on the project, while this problem is present.
the Ok(()) is actually working.. I've tried to copy-pasting all of your code before, and do cargo check i got the same problem as you write there on the comment. then I tried to clean the code inside the main function and then copy-pasting your code again piece by piece. after adding Ok(()) as the return of the main. and the error changed before I even finished the copy-pasting. see
the screenshot of different error on my local.
then I tried to fix it by adding clone() like below:
..
conf.section(Some("Server")).unwrap().clone()
..
conf.section(Some("Database")).unwrap().clone()
..
and then I cargo run it. and the server works fine! see the screenshot here.
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"
I'm using the ws crate to make a single-threaded WebSocket server. I've reproduced the problem here:
extern crate rustcord;
extern crate ws;
use rustcord::{Rustcord, User, EventHandlers};
use ws::listen;
struct Handlers;
impl EventHandlers for Handlers {
fn ready(_user: User) { }
}
fn main() {
let discord = Rustcord::init::<Handlers>("<client_id>", true, None)
.expect("Failed");
listen("127.0.0.1:8080", |out| {
move |msg| {
discord.clear_presence();
out.send(msg)
}
});
}
Here's the output from cargo check:
error[E0507]: cannot move out of `discord`, a captured variable in an `FnMut` closure
--> src/main.rs:18:9
|
14 | let discord = Rustcord::init::<Handlers>("<client_id>", true, None)
| ------- captured outer variable
...
18 | move |msg| {
| ^^^^^^^^^^ move out of `discord` occurs here
19 | discord.clear_presence();
| -------
| |
| move occurs because `discord` has type `rustcord::Rustcord`, which does not implement the `Copy` trait
| move occurs due to use in closure
Here is my Cargo.toml file:
[package]
name = "fooproject"
version = "0.1.0"
authors = ["entity100011"]
edition = "2018"
[dependencies]
ws = "=0.8.1"
rustcord = "=0.2.2"
I'm new to Rust and don't grasp the whole concept of "closures" and other Rust things. There may be other questions with the solution for this, but I can't understand the code there.