相关疑难解决方法(0)

Golang:使用其引用访问地图

我尝试遍历一个地图,我作为指向函数的指针传递,但我找不到访问元素的方法.这是代码:

func refreshSession(sessions *map[string]Session) {
    now := time.Now()
    for sid := range *sessions {
        if now.After(*sessions[sid].timestamp.Add(sessionRefresh)) {
            delete( *sessions, sid )
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此示例中的第4行返回以下编译错误:

./controller.go:120: invalid operation: sessions[sid] (type *map[string]Session does not support indexing)
Run Code Online (Sandbox Code Playgroud)

我试过括号,但没有效果.如果我带走所有引用运算符(*&),那么它编译得很好.

我该怎么写这个?

dictionary pointers go

20
推荐指数
3
解决办法
3万
查看次数

Go指针 - 通过指针将值附加到切片

我有一个结构ProductData及其实例p,它有一个slice属性:

type ProductInfo struct {
    TopAttributes []map[string]interface{}
}
Run Code Online (Sandbox Code Playgroud)

我想设置TopAttributes如下

func (p *ProductInfo) setAttributeData() {
    key := "key"
    value := "value"
    setAttribute(p.TopAttributes, key, value)
}

func setAttribute(p []map[string]interface{}, key string, value interface{}) {
    val := map[string]interface{}{
        key: value,
    }
    p = append(p, val)
}
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用.

但是,当我将方法定义为:时,还有另一种方法可以正常工作:

   func (p *ProductInfo) setAttributeData() {
    key := "key"
    value := "value"
    p.setAttribute(key, value)
}

func (p *ProductInfo) setAttribute(key string, value interface{}) {
    val := map[string]interface{}{
        key: value,
    }
    p.TopAttributes = append(p.TopAttributes, val)
}
Run Code Online (Sandbox Code Playgroud)

我想找出它为什么不起作用.我的代码中没有错误,但数据是空的.我试图这样做使它成为一个泛型函数,因为我有另一个BottomAttributes必须以相同的方式设置.

pointers go slice

16
推荐指数
2
解决办法
2万
查看次数

标签 统计

go ×2

pointers ×2

dictionary ×1

slice ×1