gpt4 book ai didi

rust - 错误 : the type of this value must be known in this context

转载 作者:行者123 更新时间:2023-11-29 07:47:47 26 4
gpt4 key购买 nike

我正在编写一个简单的 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

如何修复此代码?

最佳答案

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

let (tx, rx) = channel();

而且它还无法推断泛型类型。

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

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

关于rust - 错误 : the type of this value must be known in this context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26266313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com