2016-10-18 10 views
-2

エンドポイントにリクエストを送信し、空のインターフェイスのタイプのオブジェクトに格納されているJSON応答を受け取るサーバーコードがあります。私は情報を解析し、それをリソースである「リソース」オブジェクトのスライスに格納する必要があります。私の場合のJSONデータは、Resourceインターフェイスを満たす「Position」オブジェクトを表します。インターフェイスを入力するとコードがパニックになるのはなぜですか?

// Resource interface type 
type Resource interface { 
    // Identifier returns the id for the object 
    Identifier() bson.ObjectId 
    // Description give a short description of the object 
    Description() string 
    // Initialize should configure a resource with defaults 
    Initialize() 
    // Collection name for resource 
    Collection() string 
    // Indexes for the resources 
    Indexes() []mgo.Index 
    // UserACL returns the user access control list 
    UserACL() *UserACL 
    // IsEqual should compare and return if resources are equal 
    IsEqual(other Resource) bool 
    // Refresh should update a resource from the database 
    Refresh() 
} 

と位置モデルは次のとおりです:だから、基本的にこれらのコードは次のようになり

// Position model 
type Position struct { 
    ID  bson.ObjectId `json:"id" bson:"_id,omitempty" fake:"bson_id"` 
    Title  string  `json:"title" bson:"title" fake:"job_title"` 
    Summary string  `json:"summary" bson:"summary,omitempty" fake:"paragraph"` 
    IsCurrent bool   `json:"isCurrent" bson:"is_current,omitempty" fake:"bool"` 
    CompanyID bson.ObjectId `json:"company" bson:"company_id,omitempty" fake:"bson_id"` 
    UACL  *UserACL  `bson:"user_acl,omitempty" fake:"user_acl"` 
} 

// Identifier returns the id for the object 
func (p *Position) Identifier() bson.ObjectId { 
    return p.ID 
} 

// Description give a short description of the object 
func (p *Position) Description() string { 
    return fmt.Sprintf("[%v:%v]", p.Collection(), p.ID) 
} 
....(the other methods follow) 

私のエンドポイントは、私のデータベース内の位置のリストを取得するように設計されているので、これは明らかにすることを意味しJSONデータを含む空のインターフェイスには、リソースのスライスが含まれており、スライスにアサートされるタイプ(Goではこれを許可しない)ではなく、反復によって手動でアサインすることができます。だから私は、コードを続き、これに私の問題を分離:

func InterfaceSlice(slice interface{}) []Resource { 
    s := reflect.ValueOf(slice).Elem() 
    if s.Kind() != reflect.Slice { 
     panic("InterfaceSlice() given a non-slice type") 
    } 

    ret := make([]Resource, s.Len()) 

    for i := 0; i < s.Len(); i++ { 
     r := s.Index(i) 
     rInterface := r.Interface() 
     ret[i] = rInterface.(Resource) 
    } 

    return ret 
} 

上記のコードではすべてが

ret[i] = rInterface.(Resource) 

までうまく働いているし、その後、私のサーバーが吹くとパニックになります。私はGoのドキュメントを見て、Location型がResourceインターフェイスを満たしているため、rInterfaceがPositionモデルのデータと空のインターフェイスであっても、リソースにAssertをタイプできるはずです。私はこれを正しく理解していますか?それとも私は行方不明のものがありますか?中に、= s.Index(I) : R:

+0

パニックとは何ですか? – JimB

+0

getリクエストを送信すると、上記のコード行にトレースされるスタックトレースが取得され、50 – mudejar

+0

というパニックが発生します。そのメッセージは何ですか? – JimB

答えて

0

[OK]をKaedysは私が Rを変更することが示唆= s.Index(I).ADDR()

そして、これは明らかにトリック、問題はなかったですインターフェイスを満たすはずのオブジェクトを使用するときに発生しますが、そのオブジェクトのすべてのメソッドにはポインタ受信者があります。私はちょうどインターフェイスへの型へのポインタを配置する必要がありました。

関連する問題