2015-02-24 82 views
0

我想使用反射来调用一个结构上的方法。但是,即使attachMethodValueargs都不为零,我仍得到panic: runtime error: invalid memory address or nil pointer dereference。任何想法可能是什么?Go反映方法调用无效的内存地址或零指针解除引用

去游乐场: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.") 
} 
+0

哪条线是线29?代码恐慌 – Topo 2015-02-24 20:47:11

+0

我会认为问题出现在'val:= reflect.ValueOf(c.AppController).Elem()' – Topo 2015-02-24 20:51:50

+0

或者可能是在调用'attachMethodValue.Call(args)'时发生的事情。无论哪种方式,我们都需要错误的确切位置。 – 2015-02-24 21:15:39

回答

6

它吓坏了,因为的usermodel指针是零。我想你想:

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

playground example

相关问题