gpt4 book ai didi

generics - Rust:对通用参数的引用不满足特征限制

转载 作者:行者123 更新时间:2023-12-03 11:34:43 28 4
gpt4 key购买 nike

我正在尝试在Rust中编写一个简单的TCP客户端,询问用户是否希望其连接为SSL。我试图将尽可能多的代码抽象出来,所以我试图编写一个“communicate_with_server”函数,该函数应该能够接收SslStreamTcpStream

fn communicate_with_server<T: std::io::Read + std::io::Write>(mut stream: T) {
let initial_message = format!("hello world");
let mut buffer: Vec<u8> = Vec::new();
let _bytes_written = stream.write_all(initial_message.as_bytes());
let _flush = stream.flush();

loop {
let mut stream_reader = BufReader::new(&stream);
stream_reader.read_until(b'\n', &mut buffer).expect("Reading into buffer failed");
// ... Wait for the server to respond and do some analysis on the response ...
}
}
当我尝试编译此代码时,收到以下响应:
error[E0277]: the trait bound `&T: std::io::Read` is not satisfied
--> src\main.rs:47:48
|
47 | let mut stream_reader = BufReader::new(&stream);
| -^^^^^^
| |
| the trait `std::io::Read` is not implemented for `&T`
| help: consider removing the leading `&`-reference
|
= note: required by `BufReader::<R>::new`

error[E0599]: no method named `read_until` found for struct `BufReader<&T>` in the current scope
--> src\main.rs:49:23
|
49 | stream_reader.read_until(b'\n', &mut buffer).expect("Reading into buffer failed");
| ^^^^^^^^^^ method not found in `BufReader<&T>`
|
考虑到第一个错误,第二个错误是有意义的,但我不太确定为什么 &T不实现 Read特性。

最佳答案

&T,其中T: Read不暗示Read,因为许多Read特性方法需要对T进行突变,而这对于&T而言是不可能的,即对T的不变引用。
要解决您的问题,您应该改为将可变引用(即&mut stream)传递给BufReader::new,如下所示:

use std::io::{ Read, Write, BufReader, BufRead };

fn communicate_with_server<T: Read + Write>(mut stream: T) {
let initial_message = format!("hello world");
let mut buffer: Vec<u8> = Vec::new();
let _bytes_written = stream.write_all(initial_message.as_bytes());
let _flush = stream.flush();

loop {
let mut stream_reader = BufReader::new(&mut stream);
stream_reader.read_until(b'\n', &mut buffer).expect("Reading into buffer failed");
// ... Wait for the server to respond and do some analysis on the response ...
}
}
playground

关于generics - Rust:对通用参数的引用不满足特征限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65909797/

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