一个c代码转换成 Rust 的例子
分享链接:https://users.rust-lang.org/t/how-to-incre...
c代码:
void input(int *p)
{
int i;
for (i=0; i<=4; i++)
scanf("%d",p+i);
}
void display(int *p)
{
int i;
for(i=0;i<=4;i++)
printf("%d ", *(p+i));
}
void sort(int *p)
{
int round,t,i;
for(round=1;round<=4;round++)
{
for(i=0;i<=4-round;i++)
if(*(p+i) > *(p+i+1))
{
t = *(p+i); // a[i] *(p+i)
*(p+i) = *(p+i+1);
*(p+i+1) = t;
}
}
}
int main()
{
int a[5];
input(a);
display(a);
sort(a);
display(a);
getch();
}
sort函数对应Rust代码:
fn sort(p: &mut [u32]) { // <-- slice reference instead of raw pointer
for round in 1..p.len() { // <-- adapts to any length of array
for i in 0..p.len() - round {
if p[i] > p[i + 1] { // <-- using indexing instead of pointer arithmetic
p.swap(i, i+1); // <-- slice::swap exchanges two elements
}
}
}
}
视频求更新 :see_no_evil:
@qinplain 可能还要等一下 我平时工作996,只有周日才有空录制,我争取加快速度