如何防止其他人更改返回结构的内容

在我的程序中,我有一个缓存来存储一些结构,其他人可以使用该Get方法来获取相应的结构。如果结构包含指针(映射),我如何保护它不被其他人更改?


背景是我的同事和我在同一个包中工作,当他们使用get函数时,我只返回我的结构的副本,但如果结构包含指针,这将不起作用。我知道深拷贝可能是一个解决方案,但如果 struct 包含一些大地图,深拷贝会很痛苦。


示例代码如下:


// a.go

package foo


type bar struct {

    largeMap map[int]int

}

var cache map[int]bar

func getById(id int) bar {

    return cache[id]

}


// b.go

package foo

func fun() {

    p := getById(1)

    p.largeMap[2] = 34 // changing the original data in cache!!!!!

}


炎炎设计
浏览 121回答 2
2回答

守候你守候我

解决方案是使用 getter 函数。我们将所有非指针字段隔离在一个名为barPublicinstance 的结构中。该函数getByID将返回此结构的副本。为了从 的映射中访问值bar,我们使用专门的 getter 函数getByIDAndKey。// struct containing non pointer fields of bartype barPublic struct {    x string}type bar struct {    barPublic    largeMap map[int]int}var cache map[int]barfunc getByID(id int) (barPublic, bool) {    v, ok := cache[id]    if !ok {        return barPublic{}, false    }    return v.barPublic, true}func getByIDAndKey(id, key int) int {    v, ok := cache[id]    if !ok {        return 0, false    }    w, ok := v.largeMap[key]    if !ok {        return 0, false    }    return w, true}

RISEBY

如何防止其他人在 [Go] 中更改返回结构的内容你不能。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go