我不知道這對于語言的學習階段是否必要,但請告訴我這個主題。
我有一個結構陣列,var movies []Movie我正在用 golang 構建一個 CRUD API 專案。
當我開始撰寫對端點updateHandler的處理PUT請求時/movies/{id},我忍不住想其他方法來更新電影陣列中的物件。
原始方式(在教程視頻中)是:
// 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 request
for 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 Movie
json.NewDecoder(r.Body).Decode(&updatedMovie)
// this linq package is github.com/ahmetalpbalkan/go-linq from here
oldMovie := 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 one
oldMovie.Isbn = updatedMovie.Isbn
oldMovie.Title = updatedMovie.Title
oldMovie.Director = updatedMovie.Director
json.NewEncoder(w).Encode(oldMovie)
在這里,我的腦海中有一些事情發生了,有沒有可能像最后一種方式那樣做(我不能把 & 放在 linq 的開頭),即使有一種方法是最好的做法?
我應該像第一種方式(洗掉我們要更改的結構并插入更新的結構)還是第二種方式(分配陣列內部結構的地址并更改它)或與第二種方式相同的第三種方式(至少在我看來)但只是使用我喜歡閱讀和寫作的 linq 包?
uj5u.com熱心網友回復:
您包含的第一個案例從切片中洗掉所選專案,然后附加新專案。這需要一個看似沒有真正目的的潛在大型記憶體移動。
第二種情況你有作業,但如果意圖是替換物件的內容,有一種更簡單的方法:
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
}
}
第三個片段不回傳指標,因此您無法修改切片。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/507591.html
下一篇:如何檢查時間跨度是否為負數。C#
