You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Rust允许println!输出数组单个元素却不支持切片?

Rust中切片与单个元素访问的编译差异解析

可正常运行的代码

fn main() {
    // 创建向量
    let mut fruits = vec!("apple", "banana", "cherry", "grape");

    // 添加元素
    fruits.push("orange");  

    // 打印单个元素
    println!("Fruit vector: {:?}", fruits[2]); 
}

编译失败的代码

fn main() {
    // 创建向量
    let mut fruits = vec!("apple", "banana", "cherry", "grape");

    // 添加元素
    fruits.push("orange");  

    // 尝试打印切片
    println!("Fruit vector: {:?}", fruits[2..3]); 
}

错误信息

error[E0277]: the size for values of type `[&str]` cannot be known at compilation time
   --> src/main.rs:9:36
    |
9   |     println!("Fruit vector: {:?}", fruits[2..3]); 
    |                             ----   ^^^^^^^^^^^^ doesn't have a size known at compile-time
    |                             |
    |                             required by a bound introduced by this call
    |
    = help: the trait `Sized` is not implemented for `[&str]`

核心原因

单个元素访问fruits[2]的逻辑

fruits[2]直接返回向量中对应位置的具体元素,这里的类型是&str——它是固定大小的(包含指向字符串的指针和长度,共两个机器字),完全符合println!宏对参数的Sized约束(编译期必须知道参数的内存大小),因此可以正常编译运行。

切片访问fruits[2..3]的问题

fruits[2..3]返回的是未大小化类型[&str]。这类类型的内存大小在编译期无法确定,哪怕这个切片实际只有1个元素,Rust的切片语法本身返回的就是动态大小的数组类型。

而println!的格式化参数要求参数必须实现Sized trait,因为它需要在编译期明确参数占用的内存空间,才能正确处理参数传递。由于[&str]没有实现Sized,所以编译器抛出了错误。

快速修复

如果要打印切片,只需将其转为切片引用&[&str](固定大小类型),在切片前加&即可:

println!("Fruit vector: {:?}", &fruits[2..3]); 

内容的提问来源于stack exchange,提问作者user1245262

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 07:03:26