如何为具有固定大小的char数组创建类型别名?

时间:2014-12-18 17:18:09

标签: arrays rust

我无法弄清楚如何创建一个类型:

type CountryCode = &[char] // only 3 chars in it, no more

是否可以使用type执行此操作,还是应该使用struct

2 个答案:

答案 0 :(得分:5)

使用示例代码扩展@Levans' comment

type CountryCode = [char; 3];

fn print_it(code: CountryCode) {
    println!("{:?}", code);
}

fn main() {
    let code: CountryCode = ['u', 's', 'a'];
    print_it(code);
}

答案 1 :(得分:1)

补充@Shepmaster answer,对于像我这样的任何初学者怀疑是否可以推断类型,是的,它可以

type CountryCode = [char; 3];

fn print_country_code(code: CountryCode) {
    println!("{:?}", code);
}

fn main() {
    let explicit_code: CountryCode = ['a', 'b', 'c'];
    let implicit_code = ['d', 'e', 'f'];
    print_country_code(explicit_code);
    print_country_code(implicit_code);
}

此代码输出(如预期):

['a', 'b', 'c']
['d', 'e', 'f']

我还问自己 Rust是否执行了预期的长度,确实如此:

type CountryCode = [char; 3];

fn print_country_code(code: CountryCode) {
    println!("{:?}", code);
}

fn main() {
    let not_a_country_code = ['b', 'r'];
    print_country_code(not_a_country_code);

    let also_not_a_country_code = ['f', 'r', 'a', 'n'];
    print_country_code(also_not_a_country_code);
}

编译此代码会产生以下错误:

error[E0308]: mismatched types
  --> type_alias_for_array_fixed_size.rs:16:24
   |
16 |     print_country_code(not_a_country_code);
   |                        ^^^^^^^^^^^^^^^^^^ expected an array with a fixed size of
   |                                           3 elements, found one with 2 elements
   |
   = note: expected type `[char; 3]`
              found type `[char; 2]`

error[E0308]: mismatched types
  --> type_alias_for_array_fixed_size.rs:19:24
   |
19 |     print_country_code(also_not_a_country_code);
   |                        ^^^^^^^^^^^^^^^^^^^^^^^ expected an array with a fixed size of
   |                                                3 elements, found one with 4 elements
   |
   = note: expected type `[char; 3]`
              found type `[char; 4]`