我想从中读取自定义的字节数TcpStream,但无法初始化新的空数组缓冲区,在缓冲区中可以使用变量定义长度。由于TcpStream读取功能需要一个数组,因此无法使用向量。
let mut buffer = [0; 1024]; // The 1024 should be a variable
Run Code Online (Sandbox Code Playgroud)
当我用1024变量替换时:
let length = 2000;
let mut buffer = [0; length];
Run Code Online (Sandbox Code Playgroud)
我收到消息:
let mut buffer = [0; 1024]; // The 1024 should be a variable
Run Code Online (Sandbox Code Playgroud)
我为什么不能这样做?
使用带有with_capacity()的Vec:
use std::net::TcpStream;
fn main() {
use std::io::Read;
let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap();
let mut v = Vec::with_capacity(128);
let _ = stream.read(&mut v);
}
Run Code Online (Sandbox Code Playgroud)
你混淆了数组和切片。Rust 有不同之处:切片是内存上的一个视图,之前用数组、Vec 或其他任何东西设置。
| 归档时间: |
|
| 查看次数: |
4827 次 |
| 最近记录: |