为什么当我使用 const 初始化字符串数组时没有出现复制特征错误?

问题描述 投票:0回答:1

当我尝试用 const 初始化字符串数组时,一切都很好:

fn main() {
    const ARRAY_REPEAT_VALUE: String = String::new();
    let mut strings: [String; 5] = [ARRAY_REPEAT_VALUE; 5];
}

但是当我用不可变变量替换 const 时,出现错误:

fn main() {
    let array_repeat_value: String = String::new();
    let mut strings: [String; 5] = [array_repeat_value; 5];
}

错误是:

error[E0277]: the trait bound `String: Copy` is not satisfied                                                                 
 --> src/main.rs:3:37                                                                                                         
  |                                                                                                                           
3 |     let mut strings: [String; 5] = [array_repeat_value; 5];                                                               
  |                                     ^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String`                   
  |                                                                                                                           
  = note: the `Copy` trait is required because this value will be copied for each element of the array

即使我使用 const,我也期望得到复制特征错误。如何解释这种行为?

rust
1个回答
0
投票

关于 arrays 的文档说:

创建数组有两种语法形式:

  • 包含每个元素的列表,即
    [x, y, z]
  • 重复表达式
    [expr; N]
    ,其中
    N
    是在数组中重复
    expr
    的次数。
    expr
    必须是:
    • 实现
      Copy
      特征的类型的值
    • A
      const

因此,如果您创建数组的值是

const
,则不需要
Copy

这是有道理的,因为

const
值会在每次使用时实例化。有关更多详细信息,请参阅
const
上的文档。

© www.soinside.com 2019 - 2024. All rights reserved.