Go Reflect方法调用无效的内存地址或无指针取消引用

Poy*_*yan 0 reflection go

我正在尝试使用reflect来调用struct上的方法.但是,我得到一个panic: runtime error: invalid memory address or nil pointer dereference即使两个attachMethodValueargs是非零.关于它可能是什么的任何想法?

去游乐场: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.")
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*món 6

它会引起恐慌,因为UserModel指针是nil.我想你想要:

c := &UserController{UserModel: &UserModel{}}
Run Code Online (Sandbox Code Playgroud)

操场的例子