Type annotation on match pattern

Hello,

I am starting to play around with Rust and couldn't figure out if there is a way to type annotate the values of a Result<> in a match.

The code below shows what I mean (I didn't want to have to go to the documentation every time when I see a call to accept to figure out what it returns; I wanted to be able to define the types for _socket and addr in the match so that it is easy to understand the code just from reading it)

Thanks!

use std::net::{TcpListener, TcpStream};
use std::thread;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:9878").unwrap();
    match listener.accept() {
        // Is there a way to annotate the types of _socket and addr here?
        Ok((_socket,  addr)) => {
            thread::spawn(move || {
                println!("Got connection from {:?}", addr);
            });
        },
        Err(e) => {
            println!("Error: {:?}", e);
        }
    }
}

(Playground)

I don't think it's possible in that position, no.

Not possible, sadly. Was proposed in

You can’t do it in the pattern, but you can do something like this:

macro_rules! assert_types {
    ($($var:ident : $ty:ty),*) => { $(let _: & $ty = & $var;)* }
}

fn main() {
    let listener = TcpListener::bind("127.0.0.1:9878").unwrap();
    match listener.accept() {
        // Is there a way to annotate the types of _socket and addr here?
        Ok((_socket, addr)) => {
            assert_types! {
                _socket: TcpStream,
                addr: SocketAddr
            }
            thread::spawn(move || {
                println!("Got connection from {:?}", addr);
            });
        },
        Err(e) => {
            println!("Error: {:?}", e);
        }
    }
}
1 Like

Perhaps it's a good question to ask: why do you want this?

Non answer, but thankfully rust-analyzer shows it to me anyway on vscode
image

Otherwise I'd definitely want this.

@scottmcm

Yeah this seems pretty close to what I was looking for. I might try to revive it if I can articulate my need there. Thanks for the pointer.

@jjpe

Ease of reading the code and knowing what the variables are without having to go to the documentation to see their type.

Yeah, this is what I am looking for, but I thought there would be a native way of doing it. VIM user myself, will check for any plugins that might do that.

1 Like

coc-nvim with rust-analyzer does show the type when you position on the identifier and press Shift-K. I rely a lot on this.

You can do it in the pattern like this:

    match listener.accept() {
        Ok::<(TcpStream, SocketAddr), _>((_socket,  addr)) => {

Playground

2 Likes