2015-02-24 81 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

相關問題