我正在尝试使用反射来调用结构上的方法。但是,即使panic: runtime error: invalid memory address or nil pointer dereferenceattachMethodValue均为非零,我也得到了args。有什么想法吗?

前往游乐场: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,它感到 panic 。我想你要:

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

playground example

10-08 08:30