Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
转到python loop.last的备选方案_Python_Go_Go Templates - Fatal编程技术网

转到python loop.last的备选方案

转到python loop.last的备选方案,python,go,go-templates,Python,Go,Go Templates,我希望使用Go模板在一个数组上循环,我想在循环的最后一项中添加一个额外的字符串 {{if $hosts}}{{range $host := $hosts}} {{$host}} {{ end }} ;{{end}} 在python中,我可以 {% for host in hosts %} {{ host }}{% if loop.last %} ;{% endif %} {% endfor %} 为了实现与Go相同的目标,下面是Go等效的代码片段 {{ range $host := $hos

我希望使用Go模板在一个数组上循环,我想在循环的最后一项中添加一个额外的字符串

{{if $hosts}}{{range $host := $hosts}}
{{$host}}
{{ end }} ;{{end}}
在python中,我可以

{% for host in hosts %}
{{ host }}{% if loop.last %} ;{% endif %}
{% endfor %}
为了实现与Go相同的目标,下面是Go等效的代码片段

{{ range $host := $hosts }}
{{$host}}
{{ end }}

谢谢。

如果列表不是空的,那么Python代码片段会在最后一项后面打印一个分号。在Go中,您可以通过使用if环绕范围来检查切片中是否至少有一个元素并打印该元素来实现相同的结果;在循环之外

{{if $hosts}}{{range $host := $hosts}}
{{$host}}
{{ end }} ;{{end}}
此代码段有效,因为您要添加到最后一项的末尾。更通用的解决方案需要自定义模板函数。下面是一个示例函数:

func last(v interface{}, i int) (bool, error) {
  rv := reflect.ValueOf(v)
  if rv.Kind() != reflect.Slice {
    return false, errors.New("not a slice")
  }
  return rv.Len()-1 == i, nil
}
下面是如何在模板中使用它:

{{range $i, $host := $hosts }}
{{$host}}{{if last $hosts $i}} ;{{end}}
{{ end }}

我在操场上贴了一张便条。

另一种方法是定义减量功能,例如

“dec”:func(n int)int{return n-1},
然后,您可以使用
dec
函数计算最后一个元素,例如

{{$last := dec (len $hosts)}}
{{range $i, $host := $hosts}}
{{$host}}{{if eq $i $last}} ;{{end}}
{{end}}
当然,如果Go模板允许减法,那么编写
{{$last:=(len$hosts)-1}
就更容易了。毕竟,他们坚持在空格减号之前或之后有一个空格,所以为什么不允许简单的算术呢