英文:
Go Reflect Method Call invalid memory address or nil pointer dereference
问题
我正在尝试使用反射(reflect)在一个结构体上调用一个方法。然而,尽管attachMethodValue
和args
都不是nil,但我得到了一个panic: runtime error: invalid memory address or nil pointer dereference
的错误。有什么想法是什么原因呢?
Go Playground: http://play.golang.org/p/QSVTSkNKam
package main
import "fmt"
import "reflect"
type UserController struct {
UserModel *UserModel
}
type UserModel struct {
Model
}
type Model struct {
transactionService *TransactionService
}
func (m *Model) Attach(transactionService *TransactionService) {
m.transactionService = transactionService
}
type Transactioner interface {
Attach(transactionService *TransactionService)
}
type TransactionService struct {
}
func main() {
c := &UserController{}
transactionService := &TransactionService{}
valueField := reflect.ValueOf(c).Elem().Field(0) // 应该是 UserController.UserModel
// 尝试调用这个方法
attachMethodValue := valueField.MethodByName("Attach")
// 参数
args := []reflect.Value{reflect.ValueOf(transactionService)}
// 它们都不是nil
fmt.Printf("%+v\n", attachMethodValue)
fmt.Println(args)
// 报错!
attachMethodValue.Call(args)
fmt.Println("The end.")
}
英文:
I'm trying to use reflect to call a method on a struct. However, I'm getting a panic: runtime error: invalid memory address or nil pointer dereference
even though both the attachMethodValue
and the args
are non-nil. Any ideas on what it could be?
Go Playground: http://play.golang.org/p/QSVTSkNKam
package main
import "fmt"
import "reflect"
type UserController struct {
UserModel *UserModel
}
type UserModel struct {
Model
}
type Model struct {
transactionService *TransactionService
}
func (m *Model) Attach(transactionService *TransactionService) {
m.transactionService = transactionService
}
type Transactioner interface {
Attach(transactionService *TransactionService)
}
type TransactionService struct {
}
func main() {
c := &UserController{}
transactionService := &TransactionService{}
valueField := reflect.ValueOf(c).Elem().Field(0) // Should be UserController.UserModel
// Trying to call this
attachMethodValue := valueField.MethodByName("Attach")
// Argument
args := []reflect.Value{reflect.ValueOf(transactionService)}
// They're both non-nil
fmt.Printf("%+v\n", attachMethodValue)
fmt.Println(args)
// PANIC!
attachMethodValue.Call(args)
fmt.Println("The end.")
}
答案1
得分: 6
它恐慌是因为UserModel指针为nil。我认为你想要的是:
c := &UserController{UserModel: &UserModel{}}
英文:
It panics because the UserModel pointer is nil. I think you want:
c := &UserController{UserModel: &UserModel{}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论