我如何创建一个函数本地静态`HashSet <char>`并初始化它一次?

时间:2017-06-27 09:22:37

标签: struct static initialization rust

我已经阅读了本书的前半部分second edition以及第一版中的this chapter。我仍然对如何初始化静态变量感到困惑。

最后,我想要一个包含所有数字字符的本地静态HashSet<char>函数。

尝试1:

fn is_digit(c: char) -> bool {
    static set: std::collections::HashSet<char> =
        ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
            .iter()
            .cloned()
            .collect();

    return set.contains(&c);
}

编译器产生:

error[E0015]: calls in statics are limited to struct and enum constructors
 --> src/main.rs:3:9
  |
3 | /         ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
4 | |             .iter()
  | |___________________^
  |
note: a limited form of compile-time function evaluation is available on a nightly compiler via `const fn`
 --> src/main.rs:3:9
  |
3 | /         ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
4 | |             .iter()
  | |___________________^

尝试2 :(无数据,仅构建)

static set: std::collections::HashSet<char> = std::collections::HashSet::new();

编译器产生:

error[E0015]: calls in statics are limited to struct and enum constructors
 --> src/main.rs:1:47
  |
1 | static set: std::collections::HashSet<char> = std::collections::HashSet::new();
  |                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |

这另一方面起作用:

let set: std::collections::HashSet<char> = std::collections::HashSet::new();

HashSetstruct

这就是为什么我不理解尝试2的错误。我试图调用struct的构造函数,编译器说我只能调用struct或enum的构造函数。

我猜new()毕竟不是构造函数调用...?

1 个答案:

答案 0 :(得分:2)

要像使用其他语言(例如C ++)一样使用static变量,可以使用this crate。它会进行延迟初始化以模拟此行为。

但IMO,在你的例子中,这样的功能是矫枉过正的。你可以这样做:

fn is_digit(c: char) -> bool {
    match c {
        '0'...'9' => true,
        _ => false,
    }
}

fn main() {
    assert_eq!(is_digit('0'), true);
    assert_eq!(is_digit('5'), true);
    assert_eq!(is_digit('9'), true);
    assert_eq!(is_digit('a'), false);
}

甚至更好,使用标准:

fn is_digit(c: char) -> bool {
    c.is_digit(10)
}

关于struct,你是对的:Rust中不存在构造函数。编译器讲述了与其他对象语言中的构造函数不同的枚举构造函数。如果您想了解更多信息,最好的方法是继续阅读本书。