dongtan9465 2015-11-19 04:12
浏览 56
已采纳

Golang MongoDB(mgo)查找反射错误

With the following code

func (s Store) Lookup(department string, number string) (*types.Course, error) {
    var result *types.Course
    err := s.collection.Find(bson.M{
        "department":    department,
        "course_number": number,
    }).One(result)

    if err != nil {
        switch err {
        case mgo.ErrNotFound:
            return nil, ErrNotFound
        default:
            log.Error(err)
            return nil, ErrInternal
        }
    }

    return result, nil
}

I came across the error:

reflect: reflect.Value.Set using unaddressable value

If I change the first line from var result *types.Course to result := &types.Course{} there is no error. What exactly is the difference between these two?

  • 写回答

1条回答 默认 最新

  • douzhang1299 2015-11-19 04:40
    关注

    The two otions both declare a variable of type *types.Course. The first pointer value is nil. The second is initialized to point at a value of type types.Course.

     var result *types.Course    // result == nil
     result := &types.Course{}   // result != nil, points to a value.
     result := new(types.Course) // basically the same as the second
    

    The mgo function requires a pointer to a value. A nil pointer does not point to a value.

    The typical way to write this code is:

    var result types.Course   // declare variable of result type, not a pointer
    err := s.collection.Find(bson.M{
        "department":    department,
        "course_number": number,
    }).One(&result)           // pass address of value to function
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名