< 返回版块

17863963452 发表于 2021-02-15 19:07

Tags:如何在函数里声明数组,数组长度由变量计算

评论区

写评论
作者 17863963452 2021-02-15 20:50

谢谢

坚果修补匠 2021-02-15 19:28

原因其实很简单,数组是在栈上分配的,需要在编译的时候就能计算大小,以计算栈偏移等信息。Vec是在堆上分配的,大小编译时不知道也无所谓。

坚果修补匠 2021-02-15 19:19

这么写是不行的,数组类型长度必须为编译期常量。可以用Vec替代。

A fixed-size array, denoted [T; N], for the element type, T, and the non-negative compile-time > > constant size, N. 参考:rust官方文档

fn merge(array:&mut [f64],lo:usize,mi:usize,hi:usize)->(){
   let arr1:Vec<f64>;
}

--
👇
17863963452: ```rust fn merge(array:&mut [f64],lo:usize,mi:usize,hi:usize)->(){ let arr1:[f64,hi-lo]; }



作者 17863963452 2021-02-15 19:10
fn merge(array:&mut [f64],lo:usize,mi:usize,hi:usize)->(){
   let arr1:[f64,hi-lo];
}
1 共 4 条评论, 1 页