Golang MongoDB(mgo)查找反射错误

huangapple go评论113阅读模式
英文:

Golang MongoDB (mgo) Find reflection error

问题

通过以下代码:

  1. func (s Store) Lookup(department string, number string) (*types.Course, error) {
  2. var result *types.Course
  3. err := s.collection.Find(bson.M{
  4. "department": department,
  5. "course_number": number,
  6. }).One(result)
  7. if err != nil {
  8. switch err {
  9. case mgo.ErrNotFound:
  10. return nil, ErrNotFound
  11. default:
  12. log.Error(err)
  13. return nil, ErrInternal
  14. }
  15. }
  16. return result, nil
  17. }

我遇到了错误:

  1. reflect: reflect.Value.Set using unaddressable value

如果我将第一行从var result *types.Course更改为result := &types.Course{},就不会出现错误。这两者之间到底有什么区别?

英文:

With the following code

  1. func (s Store) Lookup(department string, number string) (*types.Course, error) {
  2. var result *types.Course
  3. err := s.collection.Find(bson.M{
  4. "department": department,
  5. "course_number": number,
  6. }).One(result)
  7. if err != nil {
  8. switch err {
  9. case mgo.ErrNotFound:
  10. return nil, ErrNotFound
  11. default:
  12. log.Error(err)
  13. return nil, ErrInternal
  14. }
  15. }
  16. return result, nil
  17. }

I came across the error:

  1. 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

得分: 6

这两个选项都声明了一个类型为*types.Course的变量。第一个指针的值为nil。第二个指针被初始化为指向一个类型为types.Course的值。

  1. var result *types.Course // result == nil
  2. result := &types.Course{} // result != nil,指向一个值
  3. result := new(types.Course) // 基本上和第二个选项一样

mgo函数需要一个指向值的指针。一个空指针不指向任何值。

通常的写法是:

  1. var result types.Course // 声明一个result类型的变量,而不是指针
  2. err := s.collection.Find(bson.M{
  3. "department": department,
  4. "course_number": number,
  5. }).One(&result) // 将值的地址传递给函数
英文:

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.

  1. var result *types.Course // result == nil
  2. result := &types.Course{} // result != nil, points to a value.
  3. 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:

  1. var result types.Course // declare variable of result type, not a pointer
  2. err := s.collection.Find(bson.M{
  3. "department": department,
  4. "course_number": number,
  5. }).One(&result) // pass address of value to function

huangapple
  • 本文由 发表于 2015年11月19日 12:12:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/33795132.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定