Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to index a slice element?

I have a slice: Keys []* datastore.Key

How could I index one of them in the template file? I guessed {{.Keys[3] }}, but that doesn't work and I searched a lot but with no clue.

Any suggestions would be welcome, thanks.

like image 706
DeanSinaean Avatar asked Oct 03 '12 03:10

DeanSinaean


People also ask

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.

What is a slice index?

Slicing is indexing syntax that extracts a portion from a list. If a is a list, then a[m:n] returns the portion of a : Starting with postion m. Up to but not including n. Negative indexing can also be used.

How do you slice a specific index in Python?

To extract elements with specific indices from a Python list, use slicing list[start:stop:step] . If you cannot use slicing because there's no pattern in the indices you want to access, use the list comprehension statement [lst[i] for i in indices] , assuming your indices are stored in the variable indices .

What is :: In slicing?

Consider a python list, In-order to access a range of elements in a list, you need to slice a list. One way to do this is to use the simple slicing operator i.e. colon(:) With this operator, one can specify where to start the slicing, where to end, and specify the step.


2 Answers

Use the index command like so:

{{index .Keys 3}} 
like image 60
nemo Avatar answered Oct 07 '22 10:10

nemo


As stated in the html/template package, the majority of examples are actually located in the text/template pkg docs. See http://golang.org/pkg/text/template/

From the docs

index     Returns the result of indexing its first argument by the     following arguments. Thus "index x 1 2 3" is, in Go syntax,     x[1][2][3]. Each indexed item must be a map, slice, or array. 
like image 20
dskinner Avatar answered Oct 07 '22 09:10

dskinner