2017-08-25 36 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

相关问题