【问题标题】:How to make an array in struct to use it in a loop?如何在结构中创建一个数组以在循环中使用它?
【发布时间】:2021-12-31 08:13:10
【问题描述】:

我在 CSV 文件中有 34 种产品,我想在 HTML 文件中使用它们中的每一种。为此,我需要一个数组键,以便我可以在 HTML 文件中一个一个地使用一个值。

问题

  • 每当我执行此代码时,它只会打印最后一个产品名称。
  • 我不知道如何在结构中创建一个数组,以便可以使用 for 循环将其用作键。

代码

type List struct {
    ProductsList string
}

func Home(w http.ResponseWriter, r *http.Request) {
    var user List
    for i := 0; i < 34; i++ {
        user = List{
            ProductsList: products.AccessData(i),
        }
    }
    HomeTmpl.Execute(w, user)
}

【问题讨论】:

    标签: arrays for-loop go structure


    【解决方案1】:

    我们可以通过像这样[]string 那样声明ProductsList 来制作一个切片(花式数组)。然后我们可以使用append 函数将元素添加到切片的末尾。这将创建一个切片的索引与i 匹配的切片。

    type List struct {
        ProductsList []string
    }
    
    func Home(w http.ResponseWriter, r *http.Request) {
        var user List
        for i := 0; i < 34; i++ {
            user.ProductsList = append(user.ProductsList, products.AccessData(i))
        }
        HomeTmpl.Execute(w, user)
    }
    

    【讨论】:

    • 谢谢你,穴居人!但是如何在 HTML 文件中显示特定产品。我写了&lt;h1&gt;{{ (index . 0).ProductsList }}&lt;/h1&gt;,但它在浏览器中什么也没显示。
    • Execute 应该返回一个错误来解释什么是错误的,始终确保检查错误返回。在这种情况下,您尝试访问 List 的索引,但列表不是切片。你想像这样访问List.ProductsList&lt;h1&gt;{{ (index .ProductsList 0) }}&lt;/h1&gt;
    • 谢谢你,穴居人! &lt;h1&gt;{{ (index .ProductsList 0) }}&lt;/h1&gt;。此代码有效。
    【解决方案2】:

    试试这个。

    我将 ProductList 属性更改为切片字符串

    type List struct {
        ProductsList []string
    }
    
    func Home(w http.ResponseWriter, r *http.Request) {
        
        AllData := []string{}
    
        for i := 0; i < 34; i++ {
            AllData = append(AllData, products.AccessData(i))
        }
    
        user := List{ ProductsList: AllData }
        // user.ProducList = ["yourdata","hello","example","and more"]
    
        HomeTmpl.Execute(w, user)
    }
    

    【讨论】:

    • 你需要:AllData = append(AllData, products.AccessData(i)) 否则切片不会在迭代中增长。
    • 好吧,我忘了这样做
    猜你喜欢
    • 2017-03-17
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 2012-05-15
    • 2011-11-15
    相关资源
    最近更新 更多