2017-08-25 91 views
2

我正在清理一些代碼,並試圖將一個結構體的切片值傳遞給函數。如何將切片元素傳遞給函數

我的結構是這樣的:

type GetRecipesPaginatedResponse struct { 
    Total  int   `json:"total"` 
    PerPage  int   `json:"per_page"` 
    CurrentPage int   `json:"current_page"` 
    LastPage int   `json:"last_page"` 
    NextPageURL string  `json:"next_page_url"` 
    PrevPageURL interface{} `json:"prev_page_url"` 
    From  int   `json:"from"` 
    To   int   `json:"to"` 
    Data  []struct { 
     ID    int  `json:"id"` 
     ParentRecipeID int  `json:"parent_recipe_id"` 
     UserID   int  `json:"user_id"` 
     Name    string `json:"name"` 
     Description  string `json:"description"` 
     IsActive   bool  `json:"is_active"` 
     IsPublic   bool  `json:"is_public"` 
     CreatedAt  time.Time `json:"created_at"` 
     UpdatedAt  time.Time `json:"updated_at"`   
     BjcpStyle struct { 
      SubCategoryID string `json:"sub_category_id"` 
      CategoryName string `json:"category_name"` 
      SubCategoryName string `json:"sub_category_name"` 
     } `json:"bjcp_style"` 
     UnitType struct { 
      ID int `json:"id"` 
      Name string `json:"name"` 
     } `json:"unit_type"` 
    } `json:"data"` 
} 

在我的代碼,我從API獲取一些JSON數據,並得到一個響應,其中包含了Data片約100個項目。

然後我在Data切片中的每個項目上循環並處理它們。

作爲一個例子,它看起來是這樣的:

for page := 1; page < 3; page++ { 
    newRecipes := getFromRecipesEndpoint(page, latestTimeStamp) //this returns an instance of GetRecipesPaginatedResponse 

    for _, newRecipe := range newRecipes.Data { 

     if rowExists(db, "SELECT id from community_recipes WHERE [email protected]", sql.Named("id", newRecipe.ID)) { 
      insertIntoRecipes(db, true, newRecipe) 
     } else { 
      insertIntoRecipes(db, false, newRecipe) 
     } 
    } 
} 

所以我想配方的實例傳遞給insertIntoRecipes功能,它看起來像這樣:

func insertIntoRecipes(db *sql.DB, exists bool, newRecipe GetRecipesPaginatedResponse.Data) { 
    if exists { 
     //update the existing record in the DB 
     //perform some other updates with the information 
    } else { 
     //insert a new record into the DB 
     //insert some other information using this information 
    } 
} 

當我運行這個,我得到的錯誤:

GetRecipesPaginatedResponse.Data undefined (type GetRecipesPaginatedResponse has no method Data)

我可以告訴問題是要做我怎麼試圖通過newRecipeinsertIntoRecipes函數,newRecipe GetRecipesPaginatedResponse.Data,但我不太確定如何傳遞它並聲明正確的變量類型。

要將Data切片內的項目傳遞給函數,當我循環切片的每個項目時,我該怎麼做?

回答

4

使用字段選擇器不能引用Data字段的匿名類型。解決方法是申報爲Data場命名類型:

type GetRecipesPaginatedResponse struct { 
    ... 
    Data  []DataItem 
    ... 
} 

type DataItem struct { 
    ID    int  `json:"id"` 
    ParentRecipeID int  `json:"parent_recipe_id"` 
    UserID   int  `json:"user_id"` 
    Name    string `json:"name"` 
    ... 
} 

使用方法如下:

func insertIntoRecipes(db *sql.DB, exists bool, newRecipe DataItem) { 
    ... 
} 

有可能是DataItem一個更好的名字。

+0

這是一種魅力,謝謝! – James