< 返回版块

zydxhs 发表于 2020-06-25 21:52

Tags:rust c

用C/C++写下面的代码很自然,怎么用Rust实现呢?

#include <stdio.h>
int main()
{
    for (char c = 'A'; c <= 'Z'; ++c)
    {
        printf("%c ", c);
    }
}

评论区

写评论
作者 zydxhs 2020-06-26 11:53

总结下:

将来可能的写法:

for i in 'A'..='Z' {
    print!("{} ", i);
}

当前可行的写法(V1.44.1): 方法一:

(b'A'..=b'Z').for_each(|c| print!("{} ", c as char));

方法二:

for i in b'A'..=b'Z' {
    print!("{} ", i as char);
}

方法三:

for i in ('A' as u8)..=('Z' as u8) {
    print!("{} ", i as char);
}
Neutron3529 2020-06-26 03:26

这样输出的是u8而非char

--
👇
Krysme:

        (b'a'..=b'z').for_each(|c| println!("{}", c));
Krysme 2020-06-26 01:28
        (b'a'..=b'z').for_each(|c| println!("{}", c));
Neutron3529 2020-06-25 22:41

可以用b'(char)'代替'(char)' as u8

这么写更简单一点

fn main(){
    for i in b'A'..=b'Z'{
        print!("{} ", i as char);
    }
}
Dengjianping 2020-06-25 22:33

1.44.1

for i in ('a' as u8)..=('z' as u8) {
    println!("{}", i as char);
}

下个版本可以了

for i in 'a'..='z' {
    println!("{}", i);
}
作者 zydxhs 2020-06-25 22:33

这种写法总感觉不够简洁,太繁琐了。

如果能支持这样的写法就好了:

for c in 'A'..='Z' {
    print!("{} ", c);
}
gwy15 2020-06-25 22:18

可以用 ..= 操作符取右闭区间。

--
👇
cnwzhjs: ``` fn main() { for c in 'A' as u8..(1 + 'Z' as u8) { print!("{} ", c as char); } }


cnwzhjs 2020-06-25 22:08
fn main() {
    for c in 'A' as u8..(1 + 'Z' as u8) {
        print!("{} ", c as char);
    }
}
1 共 8 条评论, 1 页