dongzi5062 2017-08-25 00:07
浏览 31
已采纳

如何将slice元素传递给函数

I'm in the process of cleaning some code up and am trying to pass a slice value which is a struct to a function.

My struct looks like this:

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"`
}

In my code, I fetch some JSON data from an API and get a response back that contains about 100 items in the Data slice.

I am then looping over each item in the Data slice and processing them.

As an example, it looks something like this:

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 id=@id", sql.Named("id", newRecipe.ID)) {
            insertIntoRecipes(db, true, newRecipe)
        } else {
            insertIntoRecipes(db, false, newRecipe)
        }
    }
}

So I am trying to pass the instance of a recipe to the insertIntoRecipes function, which looks like this:

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
    }
}

When I run this, I get the error:

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

I can tell that the issue is to do with how I am trying to pass the newRecipe to the insertIntoRecipes function, newRecipe GetRecipesPaginatedResponse.Data, however I am not quite sure how to pass it in and declare the right variable type.

To pass an item inside the Data slice to a function, when I am looping over each item of the Data slice, how do I do that?

  • 写回答

1条回答 默认 最新

  • duan3601 2017-08-25 00:17
    关注

    You cannot reference the anonymous type of the Data field using a field selector. The fix is to declare a named type for the Data field:

    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"`
        ...
    }
    

    Use it like this:

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

    There's probably a better name for DataItem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容