代码如下:
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::fs::read;
use std::thread;
use std::borrow::Borrow;
fn handle_client(stream: TcpStream) -> () {
let mut buffer = [0; 4096];
stream.read(&mut buffer).expect("read fail");
let path_request = String::from_utf8_lossy(&buffer[..]);
println!("request \"{}\" received", path_request);
let content_response = read(path_request.borrow()).unwrap();
stream.write(&content_response).expect("response fail");
}
编译时出现下一个错误:
error[E0283]: type annotations needed
--> src/main.rs:20:27
|
20 | let content_response = read(path_request.borrow()).unwrap();
| ^^^^ ------ type must be known at this point
| |
| cannot infer type of the type parameter `P` declared on the function `read`
问题是如何声明借用的返回类型
Cow<'_, str>
?
在当前情况下是<&str>
String::from_utf8_lossy() 返回类型为
Cow<'_, str>
且 Cow<'_, str>.borrow()
返回类型为 <&str>
因此,没有编译错误的工作代码是:
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::fs::read;
use std::thread;
use std::borrow::Borrow;
fn handle_client(stream: TcpStream) -> () {
let mut buffer = [0; 4096];
stream.read(&mut buffer).expect("read fail");
let path_request = String::from_utf8_lossy(&buffer[..]);
println!("request \"{}\" received", path_request);
let content_response = read::<&str>(path_request.borrow()).unwrap();
stream.write(&content_response).expect("response fail");
}