为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
炎炎设计 2022-05-05 17:33:23
在我的程序中,我有一个缓存来存储一些结构,其他人可以使用该Get方法来获取相应的结构。如果结构包含指针(映射),我如何保护它不被其他人更改?背景是我的同事和我在同一个包中工作,当他们使用get函数时,我只返回我的结构的副本,但如果结构包含指针,这将不起作用。我知道深拷贝可能是一个解决方案,但如果 struct 包含一些大地图,深拷贝会很痛苦。示例代码如下:// a.gopackage footype bar struct {    largeMap map[int]int}var cache map[int]barfunc getById(id int) bar {    return cache[id]}// b.gopackage foofunc fun() {    p := getById(1)    p.largeMap[2] = 34 // changing the original data in cache!!!!!}
查看完整描述

2 回答

?
守候你守候我

TA贡献1802条经验 获得超10个赞

解决方案是使用 getter 函数。


我们将所有非指针字段隔离在一个名为barPublicinstance 的结构中。该函数getByID将返回此结构的副本。为了从 的映射中访问值bar,我们使用专门的 getter 函数getByIDAndKey。


// struct containing non pointer fields of bar

type barPublic struct {

    x string

}


type bar struct {

    barPublic

    largeMap map[int]int

}


var cache map[int]bar


func 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

}


查看完整回答
反对 回复 2022-05-05
?
RISEBY

TA贡献1856条经验 获得超5个赞

如何防止其他人在 [Go] 中更改返回结构的内容

你不能。


查看完整回答
反对 回复 2022-05-05
  • 2 回答
  • 0 关注
  • 120 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号