【问题标题】:error: the type of this value must be known in this context错误:此值的类型必须在此上下文中已知
【发布时间】:2014-10-08 20:56:51
【问题描述】:

我正在编写一个简单的 TCP 聊天引擎来学习 Rust。

use std::io::{TcpListener, TcpStream};
use std::io::{Acceptor, Listener};

enum StreamOrSlice {
     Strm(TcpStream),
     Slc(uint, [u8, ..1024])
}

fn main() {
    let listener = TcpListener::bind("127.0.0.1", 5555);

    // bind the listener to the specified address
    let mut acceptor = listener.listen();

    let (tx, rx) = channel();

    spawn(proc() {
        let mut streams: Vec<TcpStream> = Vec::new();
        match rx.recv() {
            Strm(mut stream) => {
                streams.push(stream);
            }
            Slc(len, buf) => {
                for stream in streams.iter() {
                    stream.write(buf.slice(0, len));
                }
            }
        }
    });

    // accept connections and process them, spawning a new tasks for each one
    for stream in acceptor.incoming() {
        match stream {
            Err(e) => { /* connection failed */ }
            Ok(mut stream) => {
                // connection succeeded
                tx.send(Strm(stream.clone()));
                let tx2 = tx.clone();
                spawn(proc() {
                    let mut buf: [u8, ..1024] = [0, ..1024];
                    loop {
                        let len = stream.read(buf);
                        tx2.send(Slc(len.unwrap(), buf));
                    }
                })
            }
        }
    }
}

以上代码编译失败:

   Compiling chat v0.1.0 (file:///home/chris/rust/chat)
src/chat.rs:20:13: 20:29 error: the type of this value must be known in this context
src/chat.rs:20             Strm(mut stream) => {
                           ^~~~~~~~~~~~~~~~
error: aborting due to previous error
Could not compile `chat`.

这是什么原因?

值的类型已知的,它在enum 中声明为TcpStream

如何修复此代码?

【问题讨论】:

    标签: rust


    【解决方案1】:

    问题是,当您尝试匹配 rx.recv() 时,编译器不知道此表达式的类型,正如您使用泛型声明的那样

    let (tx, rx) = channel();
    

    它还没有可能推断出泛型类型。

    另外,因为它必须检查您是否正确覆盖了模式,所以它不能使用模式本身来推断类型。因此,您需要显式声明它,如下所示:

    let (tx, rx) = channel::<StreamOrSlice>();
    

    【讨论】:

      【解决方案2】:

      通过更改解决了这个问题:

              match rx.recv() {
      

      到:

              let rxd: StreamOrSlice = rx.recv();
              match rxd {
      

      看起来只是类型推断的失败。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-28
        • 1970-01-01
        • 2018-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-01
        • 1970-01-01
        相关资源
        最近更新 更多