douji8549 2014-01-22 21:48
浏览 15
已采纳

Golang无法在视图中显示检索到的数据

Hopefully this is my last question to do with pointers ever:

I am calling a repository method to get a slice of gym classes. I am displaying them in a view like this:

    {{ range .}}
            {{.VideoPath}} << Correct
            <br>
            {{.Instructor.Email}} << Blank
            <br>
            {{.ClassType.ClassTypeCode}} << Blank               
    {{end}}   

The instructor and classtype fields are coming up as empty structs, but in the ClassRepository I did some Printlns and the correct data gets printed. Somewhere there is a pointer issue or something. What have I done wrong?

Here is the repository:

package repositories    

type ClassRepository struct {
    Gorp gorp.SqlExecutor
}

func (c ClassRepository) ClassesForLastNDays(days int) []entities.Class {
    var classes []entities.Class
    // Gets the classes - omitted for brevity
    c.populateClassRelationships(classes)
    return classes
}

func (c ClassRepository) populateClassRelationships(classes []entities.Class) {
    for i := range classes {
        class := classes[i]

        // ClassType
        obj, err := c.Gorp.Get(entities.ClassType{}, class.ClassTypeCode)
        if err != nil {
            panic(err)
        }
        class.ClassType = *obj.(*entities.ClassType)
        fmt.Println(class.ClassType) << Returns correct data

        // Instructor and Equipment
        Same for instructor and Equipment


    }

}

UPDATE:

After a whole lot of printlns I can confirm that the issue is here after populateClassRelationships the populated values are all lost.

func (c ClassRepository) ClassesForLastNDays(days int) []entities.Class {
        var classes []entities.Class
        // Gets the classes - omitted for brevity
        c.populateClassRelationships(classes) <<<< In the method,Println has values
        return classes <<<< Values have been lost
    }
  • 写回答

1条回答 默认 最新

  • 普通网友 2014-01-22 23:43
    关注

    I believe the issue is with your function populateClassRelationships where it is not modifying the original data structure as illustrated by the following code which finally outputs:

    [1]
    []
    

    Not working

    func myFunc(data []int) {
        data = append(data, 1)
        fmt.Println(data)
    }
    
    func main() {
        d := []int { }
        myFunc(d)
        fmt.Println(d)
    }
    

    With the introduction of the parameters as a pointer the original data can be modified

    func myFuncNew(data *[]int) {
            *data = append(*data, 1)
        fmt.Println(*data)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置