Go 反射方法调用无效的内存地址或空指针解引用。

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

Go Reflect Method Call invalid memory address or nil pointer dereference

问题

我正在尝试使用反射(reflect)在一个结构体上调用一个方法。然而,尽管attachMethodValueargs都不是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{}}

playground示例

英文:

It panics because the UserModel pointer is nil. I think you want:

c := &UserController{UserModel: &UserModel{}}

playground example

huangapple
  • 本文由 发表于 2015年2月25日 04:12:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/28705375.html
匿名

发表评论

匿名网友

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

确定