go - Do map of pointers 与常用的maps使用方式不同

标签 go

我想用 map 创建缓存。由于 map 不允许引用其值,因此无法更改被调用函数中的值。

经过一些搜索,我发现,创建指针(结构)映射是可能的。它几乎解决了问题并且可以像引用变量一样工作 但正如我发现一些使用这种方法的 map 。我担心使用它是安全的。 有没有人有使用指针 map 的经验?这是正确的使用方式吗?

package main

import "fmt"

type Cache struct {
    name    string
    counter int
}

func incr(c Cache) {
    c.counter += 1
}
func incrp(c *Cache) {
    c.counter += 2
}

func main() {
    m := make(map[string]Cache)
    m["james"] = Cache{name: "James", counter: 10}

    c := m["james"]
    incr(c)
    fmt.Println(c.name, c.counter) // James 10

    mp := make(map[string]*Cache)
    mp["james"] = &Cache{name: "James", counter: 10}
    cp := mp["james"]
    incrp(cp)
    fmt.Println(cp.name, cp.counter) // James 12

}

edited: My text had some confusing words and sentences, that caused to misunderstanding, so i tried to fixed it

最佳答案

你可以完成这个并且仍然有一个非指针的映射,在结构上有一个指针接收器:

package main

import "fmt"

type Cache struct {
    name    string
    counter int
}

func (c *Cache) incr() {    // the '(c *Cache)' is the receiver;
    c.counter += 1          // it makes incr() a method, not just a function
}

func main() {
    m := make(map[string]Cache)
    m["james"] = Cache{name: "James", counter: 10}

    c := m["james"]
    c.incr()
    fmt.Println(c.name, c.counter)
}

输出:

James 11

如果 receiversmethods 对你来说是新的,这里是 Go 之旅中提到它们的地方:https://tour.golang.org/methods/1

在导览的几步之后注意关于指针接收器的页面:https://tour.golang.org/methods/4

关于go - Do map of pointers 与常用的maps使用方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53288885/

相关文章:

go - 如何使用 goroutine 池

go - 如何在 Go 中获取指向映射中值的指针

google-app-engine - GAE Go 运行时 SLA

go - 需要帮助理解 goroutine、select 和 channel 并发背后的逻辑

json - 从自定义 json Umarshaller 返回的错误缺少上下文

go - 如何从对象中删除属性

go - 如何通过指针访问结构数组?

Go - 如何将二进制字符串作为文本转换为二进制字节?

json - 如何将重复的子结构从一个结构复制到另一个结构?

sql - Golang时间比较无法正常工作