gpt4 book ai didi

rust - 如何使用 for 循环构造静态变量并将它们存储在静态数组中?

转载 作者:行者123 更新时间:2023-12-03 11:34:09 24 4
gpt4 key购买 nike

我需要静态变量(或与模块/文件关联的任何变量)和一个静态数组来将它们保存在同一个模块中。它们没有必要指向相同的内存。静态变量需要一个循环来初始化。这在 Rust 中可能吗?

在代码中,它看起来像下面这样。

use std::collections::HashSet;

pub struct A {
char_lens: HashSet<u8>,
}

impl A {
pub(crate) fn new(s: &'static str) -> A {
let mut char_lens: HashSet<u8> = HashSet::new();
for s in s.split_whitespace() {
char_lens.insert(s.len() as u8);
}
A { char_lens }
}
}

static VAR_A1: A = A::new("some string 1");
static VAR_A2: A = A::new("some string 2");

static A_ARRAY: [A; 2] = [VAR_A1, VAR_A2];

playground

上面的代码失败了,因为静态变量不能使用循环来初始化自己:

error[E0015]: calls in statics are limited to constant functions, tuple structs and tuple variants
--> src/lib.rs:17:20
|
17 | static VAR_A1: A = A::new("some string 1");
| ^^^^^^^^^^^^^^^^^^^^^^^

我尝试使用 lazy_static crate :

use lazy_static::lazy_static; // 1.4.0
use std::collections::HashSet;

pub struct A {
char_lens: HashSet<u8>,
}

impl A {
pub(crate) fn new(s: &'static str) -> A {
let mut char_lens: HashSet<u8> = HashSet::new();
for s in s.split_whitespace() {
char_lens.insert(s.len() as u8);
}
A { char_lens }
}
}

lazy_static! {
static ref VAR_A1: A = A::new("some string 1");
static ref VAR_A2: A = A::new("some string 2");
static ref A_ARRAY: [A; 2] = [VAR_A1, VAR_A2];
}

playground

这现在失败了,因为lazy_static 在后台为静态变量生成了一个唯一的结构。现在 VAR_A1VAR_A2具有不同的类型,并且无法引用数组的类型。

error[E0308]: mismatched types
--> src/lib.rs:21:35
|
21 | static ref A_ARRAY: [A; 2] = [VAR_A1, VAR_A2];
| ^^^^^^ expected struct `A`, found struct `VAR_A1`

最佳答案

如果您对引用没问题,只需引用并使用 deref 强制:

static ref A_ARRAY: [&'static A; 2] = [&VAR_A1, &VAR_A2];

游乐场: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=bee75c90fef228898a737ae08aa89528

如果你需要一个拥有的值,你可以使用 .clone() :

#[derive(Clone)] // For this method, we need to be able to clone.
pub struct A {
char_lens: HashSet<u8>,
}

// ...

static ref A_ARRAY: [A; 2] = [VAR_A1.clone(), VAR_A2.clone()];

游乐场: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3d48026b379e1fc3412d3f0af52286e4

关于rust - 如何使用 for 循环构造静态变量并将它们存储在静态数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62390108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com