【问题标题】:How to ensure read-only variables and maps in golanggolang中如何保证只读变量和映射
【发布时间】:2023-02-14 17:47:24
【问题描述】:

我希望我的程序能够访问全局只读正则表达式和地图。这是我的想法:

var myRegex *regexp.Regexp
var myMap map[string]string

func init() {
    myRegex = regexp.MustCompile("blah")
    myMap = map[string]string{"blah": "blah"}
}

或者我可以做

type myStruct struct {
    //  already have bunch of other struct fields
    myRegex    *regexp.Regexp
    myMap map[string]string
}


func Initialize() *myStruct {
    m := myStruct {
        // bunch of other stuff
        myRegex: regexp.MustCompile("blah")
        myMap: map[string]string{"blah": "blah"}
}

但是我如何确保这些变量不会被我的任何其他软件写入?

【问题讨论】:

    标签: go


    【解决方案1】:

    只要您处理的是指针(地图无论如何都是指针),您将永远无法确保您的地图或正则表达式是只读的。

    (好吧,除非你每次都用函数复制值并返回一个新指针......但我不确定那是你想要实现的:)

    如果我以你的例子为例,并添加一个简单的主要代码:

    package main
    
    import (
        "fmt"
        "regexp"
    )
    
    var myRegex *regexp.Regexp = regexp.MustCompile("blah")
    var myMap map[string]string
    
    func init() {
        myRegex = regexp.MustCompile("blah")
        myMap = map[string]string{"blah": "blah"}
    }
    
    type myStruct struct {
        //  already have bunch of other struct fields
        myRegex *regexp.Regexp
        myMap   map[string]string
    }
    
    func Initialize() myStruct {
        return myStruct{
            // bunch of other stuff
            myRegex: regexp.MustCompile("blah"),
            myMap:   map[string]string{"blah": "blah"},
        }
    }
    
    func getMap() map[string]string {
        return myMap
    }
    
    func main() {
        fmt.Println(myMap)
        myMap["blah2"] = "blah2"
        fmt.Println(myMap)
        fmt.Println(getMap())
    
        m := Initialize()
    
        fmt.Println(m.myMap)
        m.myMap["test"] = "test"
        fmt.Println(m.myMap)
    }
    

    你看我可以修改地图:

    ❯ ./main
    map[blah:blah]
    map[blah:blah blah2:blah2]
    map[blah:blah blah2:blah2]
    map[blah:blah]
    map[blah:blah test:test]
    

    正则表达式将完全相同。

    如果你真的想确保你的正则表达式和地图永远不会被另一段代码错误地更新,有几个解决方案;其中大部分包括将只读变量移动到自己的包中,并且从不直接访问它们。例如这样的事情

    package mapreadonly
    
    type ReadOnlyMap struct {
        m map[string]string
    }
    
    func (elem ReadOnlyMap) Get(key string) (string, bool) {
        value, ok := elem.m[key]
        return value, ok
    }
    
    var Map1 ReadOnlyMap = ReadOnlyMap{
        m: map[string]string{
            "blah": "blah",
        },
    }
    

    然后将此包导入到需要它的其他文件中。

    但如前所述,您的问题缺乏一些上下文来确保答案符合您的期望。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      相关资源
      最近更新 更多