5 个不稳定版本
0.3.1 | 2021 年 12 月 23 日 |
---|---|
0.2.2 | 2021 年 12 月 23 日 |
0.2.1 | 2021 年 12 月 22 日 |
0.2.0 | 2021 年 12 月 22 日 |
0.1.0 | 2021 年 12 月 22 日 |
#1917 在 开发工具 中
10KB
119 代码行
gpt3_macro
Rust 宏,使用 GPT3 codex 在编译时生成代码。
只需描述您想要的功能,并(可选)定义一个函数头。宏将在编译时为您生成源代码。
它还可以为您生成测试。(见示例 3)
示例 1
create_function!("checks if number is prime" fn is_prime(num: u64) -> bool);
通常将扩展为类似
// A rust function that checks if number is prime
fn is_prime(num: u64) -> bool {
if num == 2 {
return true;
}
if num % 2 == 0 {
return false;
}
let mut i = 3;
while i * i <= num {
if num % i == 0 {
return false;
}
i += 2;
}
true
}
示例 2
create_function!("prints n elements of the fibonnacci sequence to stdout" fn fib(n: u64));
有时扩展为
// prints n elements of the fibonnacci sequence to stdout
fn fib (n : u64) {
let mut a = 0;
let mut b = 1;
let mut c = 0;
for _ in 0..n {
c = a + b;
a = b;
b = c;
println!("{}", c);
}
}
示例 3:代码和测试生成
create_function_and_tests!("fizzbuzz", fn fizzbuzz(n: u64) -> String)
通常扩展为
// A rust function that fizzbuzz
fn fizzbuzz (n : u64) -> String {
if n % 15 == 0 {
"FizzBuzz".to_string()
} else if n % 3 == 0 {
"Fizz".to_string()
} else if n % 5 == 0 {
"Buzz".to_string()
} else {
n.to_string()
}
}
// 5 tests for the function
#[test]
fn test_fizzbuzz_1() {
assert_eq!(fizzbuzz(1), "1");
}
#[test]
fn test_fizzbuzz_2() {
assert_eq!(fizzbuzz(2), "2");
}
#[test]
fn test_fizzbuzz_3() {
assert_eq!(fizzbuzz(3), "Fizz");
}
#[test]
fn test_fizzbuzz_4() {
assert_eq!(fizzbuzz(4), "4");
}
#[test]
fn test_fizzbuzz_5() {
assert_eq!(fizzbuzz(5), "Buzz");
}
优点和缺点
优点 | 缺点 |
---|---|
节省编写简单实用函数的时间,将您的脑力用于解决大问题 | 编译时间大大增加 |
创建更易读的源代码——文档就是源代码。 | 您需要成为 GPT3 Codex 私有测试版的成员 |
编译时的非确定性有点有趣! | GPT3 Codex 不会总是免费的:) |
安装
在 OpenAI 账户页面 生成 OpenAI API 密钥,并设置 $OPENAI_KEY
环境变量
然后执行
cargo add gpt3_macro
或手动添加
gpt3_macro = "0.3.1"
到您的 Cargo.toml
依赖项
~2–2.8MB
~78K SLoC