gpt4 book ai didi

rust - 如何返回一个常量值?

转载 作者:行者123 更新时间:2023-11-29 08:36:20 24 4
gpt4 key购买 nike

我想写一个小的阶乘库。请查看库主模块中的代码:

pub fn results() -> const [i8; 6] { [
1,
1,
2,
6,
24,
120,
//720 is too large for i8.
] }

pub fn results() -> const [i32; 13] { [
1,
1,
2,
6,
24,
120,
720,
5_040,
40_320,
362_880,
3_628_800,
39_916_800,
479_001_600,
//6_227_020_800 is too large for i32.
] }

对于第一个函数的返回类型,它给我这个错误:

error: expected type, found keyword `const`
--> src/main.rs:1:21
|
1 | pub fn results() -> const [i8; 6] { [
| ^^^^^

目标是在编译时获取所有可能阶乘值的数组。

最佳答案

get an array of all possible factorial values at compile time

只需声明常量值:

pub const RESULTS_I8: [i8; 6] = [1, 1, 2, 6, 24, 120];

pub const RESULTS_I32: [i32; 13] = [
1,
1,
2,
6,
24,
120,
720,
5_040,
40_320,
362_880,
3_628_800,
39_916_800,
479_001_600,
];

根本没有理由涉及一个函数,因为不需要计算!

关于rust - 如何返回一个常量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51137704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com