如何修复错误 E0277:不满足 trait bound `[usize]: std::marker::Sized`? [英] How can I fix the error E0277: the trait bound `[usize]: std::marker::Sized` is not satisfied?

查看:207
本文介绍了如何修复错误 E0277:不满足 trait bound `[usize]: std::marker::Sized`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数组传递给函数:

I'm trying to pass an array to a function:

fn my_func(xs: [usize]) -> usize {
    0
}

fn main() {
    let arr = [329, 457, 657];
    let res = my_func(inp);
}

我收到错误:

error[E0277]: the trait bound `[usize]: std::marker::Sized` is not satisfied
 --> src/main.rs:1:12
  |
1 | fn my_func(xs: [usize]) -> usize {
  |            ^^ `[usize]` does not have a constant size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `[usize]`
  = note: all local variables must have a statically known size

我知道这些 其他 问题 但它们似乎不适用于我的简单情况.

I know about these other questions but they don't seem to apply to my simple situation.

如何修复错误?

推荐答案

我正在尝试将数组传递给函数

I'm trying to pass an array to a function

fn my_func(xs: [usize])

不是数组,它是一个切片;那就是问题所在.阅读切片和数组有什么区别?

This is not an array, it's a slice; that's the problem. Read What is the difference between a slice and an array?

正如其他答案所提到的,根据您的目标,有几种可能的途径可以解决问题:

As the other answers mention, there are several potential avenues to solve the problem, depending on your goals:

  • 切片 ([T]) 没有大小
  • 数组 ([T; N]) 有大小
  • 对切片 (&[T]) 的引用具有大小
  • 盒装切片 (Box<[T]>) 具有大小
  • 对数组的引用 (&[T; N]) 具有大小
  • Slices ([T]) don't have a size
  • Arrays ([T; N]) have a size
  • References to slices (&[T]) have a size
  • Boxed slices (Box<[T]>) have a size
  • References to arrays (&[T; N]) have a size

等等.

这篇关于如何修复错误 E0277:不满足 trait bound `[usize]: std::marker::Sized`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆