英文:
Golang MongoDB (mgo) Find reflection error
问题
通过以下代码:
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
}
我遇到了错误:
reflect: reflect.Value.Set using unaddressable value
如果我将第一行从var result *types.Course
更改为result := &types.Course{}
,就不会出现错误。这两者之间到底有什么区别?
英文:
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
得分: 6
这两个选项都声明了一个类型为*types.Course
的变量。第一个指针的值为nil。第二个指针被初始化为指向一个类型为types.Course
的值。
var result *types.Course // result == nil
result := &types.Course{} // result != nil,指向一个值
result := new(types.Course) // 基本上和第二个选项一样
mgo
函数需要一个指向值的指针。一个空指针不指向任何值。
通常的写法是:
var result types.Course // 声明一个result类型的变量,而不是指针
err := s.collection.Find(bson.M{
"department": department,
"course_number": number,
}).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
.
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论