Go Reflect 方法调用无效的内存地址或 nil 指针取消引用
Go Reflect Method Call invalid memory address or nil pointer dereference
我正在尝试使用反射来调用结构上的方法。但是,即使 attachMethodValue
和 args
都不为零,我也会得到 panic: runtime error: invalid memory address or nil pointer dereference
。关于它可能是什么的任何想法?
去游乐场: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.")
}
由于 UserModel 指针为 nil,它出现了混乱。我想你想要:
c := &UserController{UserModel: &UserModel{}}
我正在尝试使用反射来调用结构上的方法。但是,即使 attachMethodValue
和 args
都不为零,我也会得到 panic: runtime error: invalid memory address or nil pointer dereference
。关于它可能是什么的任何想法?
去游乐场: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.")
}
由于 UserModel 指针为 nil,它出现了混乱。我想你想要:
c := &UserController{UserModel: &UserModel{}}