我不知道這對于學習語言階段是否必要,但請告訴我這個問題。我有一個結構數組var movies []Movie,我正在用 golang 構建一個 CRUD API 項目。當我開始編寫對端點updateHandler的處理PUT請求/movies/{id}時,我忍不住想其他方法來更新 movies 數組中的對象。原來的方式(在教程視頻中)是:// loop over the movies, range// delete the movie with the id that comes inside param// add a new movie - the movie that we send in the body of requestfor index, item := range movies { if item.ID == params["id"] { movies = append(movies[:index], movies[index+1:]...) var updatedMovie Movie json.NewDecoder(r.Body).Decode(&updatedMovie) updatedMovie.ID = params["id"] movies = append(movies, updatedMovie) json.NewEncoder(w).Encode(updatedMovie) }}但在我觀看之前,我嘗試編寫自己的方法,如下所示:for index, item := range movies { if item.ID == params["id"] { oldMovie := &movies[index] var updatedMovie Movie json.NewDecoder(r.Body).Decode(&updatedMovie) oldMovie.Isbn = updatedMovie.Isbn oldMovie.Title = updatedMovie.Title oldMovie.Director = updatedMovie.Director json.NewEncoder(w).Encode(oldMovie) // sending back oldMovie because it has the id with it }}如您所見,我將數組索引的指針分配給了一個名為 oldMovie 的變量。我也想過另一種方法,但不太順利var updatedMovie Moviejson.NewDecoder(r.Body).Decode(&updatedMovie)// this linq package is github.com/ahmetalpbalkan/go-linq from hereoldMovie := linq.From(movies).FirstWithT(func(x Movie) bool { return x.ID == params["id"]}).(Movie) // But here we'r only assigning the value not the reference(or address or pointer) // so whenever i try to get all movies it still returning // the old movie list not the updated oneoldMovie.Isbn = updatedMovie.IsbnoldMovie.Title = updatedMovie.TitleoldMovie.Director = updatedMovie.Directorjson.NewEncoder(w).Encode(oldMovie)在這里我腦子里想著一些事情是否有可能像最后一種方法那樣做(我不能把 & 放在 linq 的開頭)即使有什么方法是最好的做法?我應該像第一種方式那樣做(刪除我們要更改的結構并插入更新的結構)還是第二種方式(分配數組內部結構的地址并更改它)或與第二種方式相同的第三種方式(至少在我看來)但只是使用我喜歡閱讀和寫作的 linq 包?
1 回答

慕桂英3389331
TA貢獻2036條經驗 獲得超8個贊
您包含的第一個案例從切片中刪除所選項目,然后附加新項目。這需要一個看似沒有真正目的的潛在大 memmove。
第二種情況有效,但如果目的是替換對象的內容,則有一種更簡單的方法:
for index, item := range movies {
if item.ID == params["id"] {
json.NewDecoder(r.Body).Decode(&movies[index])
// This will send back the updated movie
json.NewEncoder(w).Encode(&movies[index])
// This will send back the old movie
json.NewEncoder(w).Encode(item)
break // Break here to stop searching
}
}
第三個片段不返回指針,因此您不能修改切片。
- 1 回答
- 0 關注
- 114 瀏覽
添加回答
舉報
0/150
提交
取消