将切片返回到常量数组

Returning slices to a constant array

我有一个很大的浮点数常量数组(网格坐标),想 return 它的各种切片用于 OpenGL。以下编译失败:

const VERTICES: [f32; 10] = [
  0.0, 0.0, 0.0,
  0.0, 0.0,
  1.0, 0.0, 0.0,
  1.0, 0.0];

pub fn vertex_coords() -> &'static [f32] {
  &VERTICES
}

pub fn texture_coords() -> &'static [f32] {
  &VERTICES[3..]
}
<anon>:8:4: 8:12 error: borrowed value does not live long enough
<anon>:8   &VERTICES
            ^~~~~~~~
note: reference must be valid for the static lifetime...
<anon>:7:42: 9:2 note: ...but borrowed value is only valid for the block at 7:41
<anon>:7 pub fn vertex_coords() -> &'static [f32] {
<anon>:8   &VERTICES
<anon>:9 }
<anon>:12:4: 12:12 error: borrowed value does not live long enough
<anon>:12   &VERTICES[3..]
             ^~~~~~~~
note: reference must be valid for the static lifetime...
<anon>:11:43: 13:2 note: ...but borrowed value is only valid for the block at 11:42
<anon>:11 pub fn texture_coords() -> &'static [f32] {

这也失败了:

pub fn vertex_coords<'a>() -> &'a [f32] {

知道怎么做吗?

constantsstatics 两个概念之间存在重要区别。这些是 Rust 中不同的概念。引入时的区别的详细设计可以在RFC 246.

中找到

值得关注的内容:

Therefore, taking the address of a constant actually creates a spot on the local stack -- they by definition have no significant address.

有了这个理解,就可以看出为什么对常量的引用不会产生 'static 借用——它 不是 静态引用,它是引用本地堆栈中的内容。

有两种处理方法;一种是使类型成为静态引用(&'static [f32; 10]&'static [f32]),其中 VERTICES 可以是 &'static [f32] 类型(如果常量具有该类型)并且 &VERTICES[3..] 将是 &'static [f32] 类型。因为没有有效地址并被放置在本地堆栈上的东西是 'static 引用——它所指的是 确实 因此必然有一个固定地址。

另一种方法(可能是首选方法)是使用 static 而不是 const。这样你就可以毫无阻碍地对它进行静态引用。

等等:

static VERTICES: [f32; 10] = [
    0.0, 0.0, 0.0,
    0.0, 0.0,
    1.0, 0.0, 0.0,
    1.0, 0.0];

pub fn vertex_coords() -> &'static [f32] {
    &VERTICES
}

pub fn texture_coords() -> &'static [f32] {
    &VERTICES[3..]
}