为什么我不能写一个与 Box::new 相同类型的函数? [英] Why can't I write a function with the same type as Box::new?
问题描述
如果我编写的函数采用 [f32]
类型的一个参数(而不是例如 &[f32]
),我会收到一个错误:>
If I write a function that takes one argument of type [f32]
(as opposed to e.g. &[f32]
), I get an error:
the trait bound `[f32]: std::marker::Sized` is not satisfied
文档说这是因为 [f32]
没有编译时已知的大小.一个合理的限制.很公平.
The docs say this is because [f32]
does not have a compile-time-known size. A reasonable limitation. Fair enough.
但是,标准库中至少有一个函数是这种类型的.这是我的称呼:
However, there is at least one function in the standard library with this type. Here's me calling it:
let b: Box<[f32]> = Box::new([1.0, 2.0, 3.0]);
为什么这在标准库中是允许的,而不是在我的代码中?相关区别是什么?(来源).
How come this is allowed in the standard library and not in my code? What is the relevant difference? (There's no obvious magic in the source).
推荐答案
[f32]
未调整大小.但是, [1.0, 2.0, 3.0]
是大小...它的类型是 [f32;3]
.
[f32]
is unsized. However, [1.0, 2.0, 3.0]
is sized... its type is [f32; 3]
.
这就是使用标准库代码编译时 T
的样子,一个 [f32;3]
大小的数组.
That's what T
will be when compiled with the standard library code, an [f32; 3]
sized array.
要自己接受一个大小的数组,你可以这样做:
To accept a sized array yourself, you can do the same:
fn my_func(array: [f32; 3]) {
// Implementation here
}
my_func([1.0, 0.0, 0.0]);
点击此处查看工作示例在操场上
&[f32]
切片也有大小.. 这就是它也被允许的原因.
An &[f32]
slice is sized too.. which is why it is allowed also.
正如 Lukas 在评论中指出的,切片是一个胖指针"(您可以在 Nomicon 中阅读有关动态大小类型的信息).切片胖指针由一个指向一段数据的指针和一个表示该数据有多大的值组成.
As Lukas points out in the comments, slices are a "fat pointer" (You can read about Dynamically Sized Types in the Nomicon). Slice fat pointers consist of a pointer to a piece of data and a value representing how big that data is.
这篇关于为什么我不能写一个与 Box::new 相同类型的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!