我不知道這對于學(xué)習(xí)語言階段是否必要,但請告訴我這個(gè)問題。我有一個(gè)結(jié)構(gòu)數(shù)組var movies []Movie,我正在用 golang 構(gòu)建一個(gè) CRUD API 項(xiàng)目。當(dāng)我開始編寫對端點(diǎn)updateHandler的處理PUT請求/movies/{id}時(shí),我忍不住想其他方法來更新 movies 數(shù)組中的對象。原來的方式(在教程視頻中)是:// 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 }}如您所見,我將數(shù)組索引的指針分配給了一個(gè)名為 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 的開頭)即使有什么方法是最好的做法?我應(yīng)該像第一種方式那樣做(刪除我們要更改的結(jié)構(gòu)并插入更新的結(jié)構(gòu))還是第二種方式(分配數(shù)組內(nèi)部結(jié)構(gòu)的地址并更改它)或與第二種方式相同的第三種方式(至少在我看來)但只是使用我喜歡閱讀和寫作的 linq 包?
1 回答

慕桂英3389331
TA貢獻(xiàn)2036條經(jīng)驗(yàn) 獲得超8個(gè)贊
您包含的第一個(gè)案例從切片中刪除所選項(xiàng)目,然后附加新項(xiàng)目。這需要一個(gè)看似沒有真正目的的潛在大 memmove。
第二種情況有效,但如果目的是替換對象的內(nèi)容,則有一種更簡單的方法:
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
}
}
第三個(gè)片段不返回指針,因此您不能修改切片。
- 1 回答
- 0 關(guān)注
- 121 瀏覽
添加回答
舉報(bào)
0/150
提交
取消