如何编写一个可用于初始化静态变量的函数?

huangapple go评论81阅读模式
英文:

How can I write a function that can be used to initialize a static?

问题

这段代码中的问题是这样的:

这段代码可以正常工作:

static mutex: std::sync::Mutex<Object> =
    std::sync::Mutex::new(Object { field: BTreeMap::new() });

但这段代码却不能正常工作:

static mutex: std::sync::Mutex<Object> =
    std::sync::Mutex::new(Object::new());

struct Object {
    field: BTreeMap<String, String>,
}

impl Object {
    fn new() -> Object {
        Object { field: BTreeMap::new() }
    }
}

问题出在 Object::new() 这个方法上,它返回的是 Object 的新实例,但是这个实例没有被包裹在 std::sync::Mutex 中。正确的解决方法是确保 Object::new() 返回的实例被正确包裹在 Mutex 中,就像第一个示例中那样。

解决方法是将 Object::new() 修改为返回一个被 Mutex 包裹的实例,如下所示:

static mutex: std::sync::Mutex<Object> =
    std::sync::Mutex::new(Object::new());

struct Object {
    field: BTreeMap<String, String>,
}

impl Object {
    fn new() -> Object {
        Object { field: BTreeMap::new() }
    }
}

这样,你的代码就会正常工作了。

英文:

This works:

static mutex: std::sync::Mutex&lt;Object&gt; =
    std::sync::Mutex::new(Object { field: BTreeMap::new() });

and this does not:

static mutex: std::sync::Mutex&lt;Object&gt; =
    std::sync::Mutex::new(Object::new());

struct Object {
    field: BTreeMap&lt;String, String&gt;,
}

impl Object {
    fn new() -&gt; Object {
        Object { field: BTreeMap::new() }
    }
}

Why, and what is the resolution?

答案1

得分: 1

一个函数只有在被标记为const时才能作为static变量的初始化器使用,这意味着它可以在编译时求值。

const函数内只有有限的功能可用。幸运的是,你的new()函数中的所有内容都与const兼容,因此将const关键字添加到你的函数将修复编译器错误。

use std::collections::BTreeMap;

static mutex: std::sync::Mutex<Object> = std::sync::Mutex::new(Object::new());

struct Object {
    field: BTreeMap<String, String>,
}

impl Object {
    const fn new() -> Object {
        Object {
            field: BTreeMap::new(),
        }
    }
}
英文:

A function can only be used as an initializer for a static variable if the function is marked const, meaning, it can be evaluated at compile time.

Only a limited amount of functionality is available inside of a const function. Luckily everything in your new() function is compatible with const, so adding the const keyword to your function will fix your compiler error.

use std::collections::BTreeMap;

static mutex: std::sync::Mutex&lt;Object&gt; = std::sync::Mutex::new(Object::new());

struct Object {
    field: BTreeMap&lt;String, String&gt;,
}

impl Object {
    const fn new() -&gt; Object {
        Object {
            field: BTreeMap::new(),
        }
    }
}

huangapple
  • 本文由 发表于 2023年8月5日 03:06:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76838593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定