<分区>
我已经通读了这本书的前半部分second edition以及this chapter在第一版中。我仍然对如何初始化静态变量感到困惑。
最后我想要一个函数 local static 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();
HashSet
是 struct
.
这就是为什么我不理解尝试 2 的错误。我正在尝试调用结构的构造函数,但编译器说我只能调用结构或枚举的构造函数。
我猜 new()
毕竟不是构造函数调用...?