Reputation: 871
Good evening. I am trying to build a websockets client in Rust. My main coding experience comes from python so I tried to follow this repo: https://github.com/bedroombuilds/python2rust/tree/main/23_websockets_client/rust/ws_client
I just want to listen to a channel and print to the screen; so the logic from the tokio::select!
in the snippet is not being used in my implementation. But if I do this:
let ws_msg = ws_stream.next();
{
match ws_msg {
Some(msg) => match msg {
...
It won't compile because it cannot match ws_msg
:
error[E0308]: mismatched types
--> src/main.rs:145:22
|
144 | match ws_msg {
| ------ this expression has type `Next<'_, WebSocketStream<tokio_tungstenite::stream::Stream<tokio::net::TcpStream, tokio_tls::TlsStream<tokio::net::TcpStream>>>>`
145 | Some(msg) => match msg {
| ^^^^^^^^^ expected struct `Next`, found enum `Option`
|
= note: expected struct `Next<'_, WebSocketStream<tokio_tungstenite::stream::Stream<tokio::net::TcpStream, tokio_tls::TlsStream<tokio::net::TcpStream>>>>`
found enum `Option<_>`
Still, if I just keep the tokio::select!
macro with just one branch then it is okay. That is, this code compiles and runs:
tokio::select! {
ws_msg = ws_stream.next() => {
match ws_msg {
Some(msg) => match msg {
My question is: is the assignment ws_msg = ws_stream.next()
inside the select!
doing something different than the one inside the let
? (I mean, evidently that seems to be the case, but from the select!
docs I just cannot infere what is the difference.
Any help is much appreciated!! Thanks in advance.
Upvotes: 1
Views: 699
Reputation: 155206
You should match on ws_stream.next().await
.
I expect tokio::select!()
does the awaiting, as well as actual selecting between the two futures, for you under the hood. It then runs the code corresponding to the future that finished first, giving it the value obtained by await, and it is the awaited value that the original code matches on. If you only have one stream, then you don't need select!()
, but you now need the explicit .await
.
Upvotes: 1