![](/img/trans.png)
[英]Why does python 3 tell me that there is no such file or directory when I use test.json in my code
[英]Why does my code panic when I type assert an interface?
我有一些服務器代碼向端點發送請求並接收存儲在空接口類型的對象中的 JSON 響應。 我必須解析信息並將其存儲在“資源”對象的切片中,資源是一個接口。 在我的例子中,JSON 數據代表一個“Position”對象,它滿足 Resource 接口。 所以基本上這些代碼看起來像這樣:
// 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 文檔,據我所知,即使 rInterface 是一個帶有 Position 模型數據的空接口,我也應該能夠在 Resource 中輸入 assert ,因為 Position 類型無論如何都滿足 Resource 接口。 我的理解正確嗎? 或者有什么我想念的嗎?
Ok Kaedys 建議我將 r := s.Index(i) 改為: r := s.Index(i).Addr()
這確實奏效了,顯然當您使用一個應該實現接口的對象時會出現問題,但是該對象上的所有方法都有指針接收器。 我只需要在接口中放入一個指向類型的指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.