golang iterate over slice. The most basic way to iterate through an array or slice is by using the traditional for loop, where you define a loop counter and access each item by its index. golang iterate over slice

 
The most basic way to iterate through an array or slice is by using the traditional for loop, where you define a loop counter and access each item by its indexgolang iterate over slice  example

Strings can be constructed from a slice of bytes. It may look like Lodash in some aspects. When you call range on a collection, the go runtime initialises 2 memory locations; one for the index (in this case _), and one for the value cmd. A slice. values ()) { // code logic } First, all Go identifiers are normally in MixedCaps, including constants. range statement where it fetches the index and its corresponding value. someslice[min:max]), the new slice will share the backing array with the original one. To generate HTML output, see html/template, which has the same interface as this package but automatically secures HTML output against certain attacks. So after the latter example executes, all your x direction arrays are empty, indexing into one causes a panic. We can. We then iterate over the slice numbers using a for-range loop. A slice is a dynamically-sized, flexible view into the elements of an array. Summary. – Before sorting: Slice 1: [Python Java C# Go Ruby] Slice 2: [45 67 23 90 33 21 56 78 89] After sorting: Slice 1: [C# Go Java Python Ruby] Slice 2: [21 23 33 45 56 67 78 89 90] Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. In Go we use the keyword range within a for loop construct to iterate over a slice. In this example, we use a for loop to iterate over a range of integers from start (1) to end (5) inclusive. It gets the job done simply and effectively by swapping array items front to back, an operation that's efficient in the random-access structure of arrays. Using the range keyword: The range form of the for loop iterates over a slice or map. From practical use-cases to memory management, let’s navigate through slices seamlessly together. To create Integer Array, which is to declare and initialize in a single line, we can use the syntax of array to declare and initialize in one line as shown in the following. The long answer is still no, but it's possible to hack it in a way that it sort of works. A []Person and a []Model have different memory layouts. Params. Iterating over slices and arrays. This slice could be a local variable, or it could be the result of calling some function that returns a slice. Body to json. ReadAll returns a []byte, no need cast it in the next line; better yet, just pass the resp. Looks like it works with single item marked to remove, but it will fail soon with panic: runtime error: slice bounds out of range, if there are more than one item to remove. Explanation:-In the above code, we are using for range loop to iterate through a slice of string values and appending its values to a struct as key and value of integer and string type respectively. . Golang is an awesome, simple, modern, and fast programming language. As mentioned by @LeoCorrea you could use a recursive function to iterate over a slice. arraySize is the number of elements we would like to store in. Method 1:Using for Loop with Index In this method,we will iterate over a You can iterate over the map in order by sorting the keys explicitly first, and then iterate over the map by key. In Golang Range keyword is used in different kinds of data structures in order to iterates over elements. }, where T is the type of n (assuming x is not modified in the loop body). Golang mutate a struct's field one by one using reflect. Meanwhile, function ReturnSliceWithPointers looks worse: less performance and less memory efficiency. Your slices sample isn't random but a known index. But you supply a slice, so that's not a problem. In the meantime, doing this with a loop is clear and concise enough. }, where T is the type of n (assuming x is not modified in the loop body). This will fail your code. In the beginning I made some very bad mistakes iterating over slices because I. Right now I have a messy switch-case that's not really scalable, and as this isn't in a hot spot of my application (a web form) it seems leveraging reflect is a good choice here. – mkoprivaThis is a slice literal, you should use Golang built-in function append with it. Output. [1:4] creates a slice representation of the array a starting from indexes 1 through 3. I get the output: 0: argument_1 1: argument_2 // etc. 1. If you require a stable iteration order you must maintain a separate data structure that specifies that order. The code sample above, generates numbers from 0 to 9. I was wondering whether there's any mechanism to iterate over a map that is capable of suspending the iteration and resuming it later. Programmers had begun to rely on the stable iteration order of early versions of Go, which varied between. The operands go on either side of this operator symbol. An exported field named "FOO" or "FoO" or some other case-insensitive match of "Foo". 2. When you need to store a lot of elements or iterate over elements and you want to be able to readily modify those elements, you’ll likely want to work with the slice. That being said, it's probably easier to just access the exported variables the "normal" way. The iteration order is intentionally randomised when you use this technique. Step 6 − Run another loop in nested form and check if the elements in the first slice are equal to the elements in the second slice. The reflect package allows you to inspect the properties of values at runtime, including their type and value. The first time we print the value of the slice integers, we see all zeros. it is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. Iterating over the values. A list in Golang, specifically referring to the container/list package, is a versatile and dynamic data structure used for storing and managing elements. Step 4 − Set up a second for loop and begin iterating through the. Similar to how we declare the type of key and value while defining a map, since values are also maps, to define a map x with keys of string type, and values of type map [string]string, use the following code. Slices have a capacity and length property. Whereas, ReadDir only performs a single system call and returns a slice of DirEntry, which contains Name(), IsDir(), and Info(). length <= 7 }Check if Array contains Specific Element. Looping through slices. If it's possible that more than one element will be deleted, then use. Two-result iterators. – Cerise Limón. Modifying a Go slice in-place while iterating over it. After that, we use for-range to print each element on a new line. For example, this gets a slice of the elements s[2], s[3], and s[4]. The syntax to use for loop for a range x is. 1) if a value is a map - recursively call the method. However, there is a recent proposal by RSC that extends the range to iterate over integers. It can be used here in the following ways: Example 1: When you need to store a lot of elements or iterate over elements and you want to be able to readily modify those elements, you’ll likely want to work with the slice data type. In some cases, you might want to modify the elements of a slice. Iterating through a golang map. To iterate over a slice in Go, create a for loop and use the range keyword: package main import ( "fmt" ) func main() { slice := []string{"this", "is", "a", "slice", "of",. The first law of reflection. The most basic way to iterate through an array or slice is by using the traditional for loop, where you define a loop counter and access each item by its index. In order to get an intersection of two slices in Go (Golang) you don't need any external library you can use everything that is available already in the Go (Golang) standard library. . However, you can define slices or arrays of enum values and iterate over those, or you could define a range of valid enum values and iterate over the integers within that range, converting each integer to the corresponding enum value. To get length of slice in Go programming, call len() function and pass the slice as argument to it. Println(b) // Prints [0 0 0 0 0 0 0 0 0 0 1 2]Iterate over Characters of String. 4. Instead we could put pointers of type *MyStruct inside the slice. When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next. Step 8 − If the elements of both slices are not equal return false but if they are equal return true to the function. 39. iterate Map / Dictionary in golang template. The value can be a constant or based on the element itself. Scan (&firstName, &lastName, &GPA) applicants = append (applicants, Applicant {firstName, lastName, GPA}) Now my task is to output only names of first 3 applicants with highest GPA. Printf("index: %d, value: %d ", i, numbers[i]) } } Output Prepare every slice as a map: m1 := make(map[int]string) for i:=0; i < len(s1); i ++ { m1[s1[i]. The conditional for-loop in Golang. Use maps in Go templates. In Go programming, we can also create a slice from an existing array. slice(0, until); Now here is the tricky part. Golang – String to uppercase. > "golang-nuts" group. go package main import ( "fmt" ) func main() { numbers := []int{1, 10, 100, 345, 1280} for i := len(numbers) - 1; i >= 0; i-- { fmt. To loop through a slice, we can use the range keyword, just like we did with arrays. 1 I am taking the "Tour of Go", and had a question regarding the Exercise: Slices example. array. (or GoLang) is a modern programming language originally developed by Google that uses high-level syntax similar to scripting languages. Which is the best procedure (easier to write and understand) to break this slice into 3 parts, for example, and distribute the content in three sub-slices? If I have: var my_sub_slice1 []string var my_sub_slice2 []string var my_sub_slice3 []stringWhat is the correct way to create a new slice in Golang? A) slice := make([]. Call method on any array of structs that have underlying field. 1. type Attribute struct { Key, Val string } type Node struct { Attr []Attribute } and that I want to iterate on my node's attributes to change them. Similar to the concurrent slices and the fact that we have used interface{} to store the map values we need to use type assertions in order to retrieve the underlying value. An array holds a fixed number of elements, and it cannot grow or shrink. 7. Line 7: We declare and initialize the slice of numbers, n. Then we iterate through each index and set the value to the current index. g. It will cause the sort. Any modifications you make to the iteration variables won’t be reflected outside of the loop. The range keyword allows you to loop over each key-value pair in the map. Here we will see how to construct a string from slices of bytes and runes. Arrays had a slight edge over slices when iterating over the entire dataset due to better memory. Go has strings. During each iteration, range can return one or two values based on the type of collection you are iterating. Example implementation: type Key int // Key type type Value int // Value type type valueWrapper struct { v Value next *Key } type Map struct { m map. The syntax of Replace. To do this task, I decided to use a slice of struct. Share . Golang NOT. and thus cannot be used as a map-key. That. In Go, in order to iterate over an array/slice, you would write something like this: for _, v := range arr { fmt. A nil slice declared as var s1 []string has no underlying data array - it points to nothing. I am trying to write a simple program that creates a struct called 'person' which accepts firstname, lastname, and age. B), I want to iterate through the fields because I have 100 fields in the struct so doesn't make sense to do v. Image 1: Slice representation. Number of fields: 3 Field 1: Name (string) = Krunal Field 2: Rollno (int) = 30 Field 3: City (string) = Rajkot. html. For each class type there are several classes, so I want to group all the Yoga classes, and all the Pilates classes and so on. In Python, I can write it out as follows: Change values while iterating. I would like to recreate that example but instead be able to pass in a slice of int or slice of float instead, and in the function I'll just sum up everything in the slice. type Person struct { ID int NAME string } Example of a slice of structs [{1 John},{2, Mary},{3, Steven},{4, Mike}] What I want in index. 70. /. If so, my guess as to why the output is exactly 0A, 1M, 2C, - because, originally, the slice was passed to the loop by pointer, and when the capacity of the slice is doubled in the first iteration of the loop, the print(i, s). c:= make ([] string, len (s)) copy (c, s) fmt. and in last we’re going to use Variadic function approach to get sum of. The following example uses range to iterate over a Go array. Let’s ignore the ProduceAlbum function for now, and see how slices of values and slices of pointers compare structurally. Looping through array elements in GoLang in the html/template. As I understand range iterates over a slice, and index is created from range, and it's zero-based. They are one of the most commonly used data structures in Golang. When it iterates over the elements of an array and slices then it returns the index of the element in an integer. (map [string]interface {}) ["foo"] It means that the value of your results map associated with key "args" is of. The rest of the function is very simple. 0. golang size of slice; golang sort slice descending; golang create empty slice of specified length; go delete from slice; sort int slice in golang; go add to slice; go iterate over slice; go slice pop; golang iterate reverse slice; interface to array golang; append a slice to a slice golang; slice in golang; golang slice; convert slice to unique. Just use a type assertion: for key, value := range result. Go Ranges. There is no built in i'm aware of that lets you iterate over all the exported variables in a vars block. a [x] is the slice element at index x and the type of a [x] is the element type of S. Also for small data sets, map order could be predictable. Pointer: The pointer is used to point to the first element of the array that is accessible through the slice. If the content mostly false and bigger n then better map should be more memory efficient. body, _ := ioutil. 10. ReadAll returns a []byte, no need cast it in the next line; better yet, just pass the resp. Declare a Slice. image: golang:latest pull: always ruleset: event: [ push, pull. To guarantee a specific iteration order, you need to create some additional data. Golang – Iterate over Range using For Loop; Golang Map. Readdir goes through every file in the directory and calls Lstat() (system call) to return a slice of FileInfo. Since rune can be larger than a single byte (1 to 4 bytes), you can't really check the next item in the slice, since some chars (other than ASCII) can be larger than a single byte. Share. In this example, we create a map numberMap. The iteration values are assigned to the respective iteration variables, i and s , as in an assignment statement. If the argument type is a type parameter, all types in its type set must be maps or slices, and clear performs the operation corresponding to the actual type argument. 18. Given the following code I would expected an infinite loop but the loop is being stopped at certain point. html", a). So, the way suggest is to hold the keys in a slice and sort that slice. Range through an arbitrary number of nested slices of structs in an HTML template in Go. The rangeform of the for loop iterates over a slice or map. Since Go 1. In this tutorial, we will learn the syntax of Floor () function, and how to use this function to find the floor value of a given number. Golang Slice; Golang – Slice Length; Golang – Iterate over Slice using For Loop; Golang – Check if Specific Element is present in Slice; Golang – Sort Slice of Strings; Golang – Sort Slice of Integers; Golang Struct. To get started, there are two types we need to know about in package reflect : Type and Value . Pointer, length C. Println (i, s) } The range expression, a, is evaluated once before beginning the loop. To iterate over elements of a slice using for loop, use for loop with initialization of (index = 0), condition of (index < slice length) and update of (index++). I am trying to display a list gym classes (Yoga, Pilates etc). This can be seen in the function below: func Reverse(input []int) [] int { var output [] int for i := len (input) - 1; i >= 0; i-- { output = append (output, input [i]) } return output }I want to pass a slice that contains structs and display all of them in the view. This is a linear time, cache efficient solution in less code. Firstly we will iterate over the map and append all the keys in the slice. Println ("Hello, playground") var foo []string // nil slice. }},{{end}}` BenchmarkGoLoop-10 1283661 919. Field(), you get a reflect. UserCreatedEntity is an interface, and Idea satisfies the interface, so you can return an Idea from a function whose signature has a return type of UserCreatedEntity. First we can modify the GreetHumans function to use Generics and therefore not require any casting at all: func GreetHumans [T Human] (humans []T) { for _, h := range humans { fmt. Pointer: The pointer is used to point to the first element of the array that is accessible through the slice. Store keys to the slice. Example. Book B,C,E belong to Collection 2. That's going to be less efficient than just iterating over the three slices separately, especially if they're quite large. Golang Slice provides many inbuilt functions, which we will go through them in this tutorial. Iterating over the values. slice(from, until); From: Slice the array starting from an element index; Until: Slice the array until another element index; For example, I want to slice the first three elements from the array above. Every time map look up for a key, it needs to search for its content. ranging over a slice, you get the individual element which is then passed to reflect, it does not retain any info that it was part of a []interface{} so you get the value directly indexing the slice, the slice element is a known to be a interface{} (because you passed reflect a []interface{} ) and you have to work through the type system and. Split () function. In this code example, we defined a Student struct with three fields: Name, Rollno, and City. If the letter exist, exit the loop. 1 Answer. fmt. I am trying to iterate over a map of interfaces in golang, it has the below structure, I am able to use for loop to iterate to a single level but couldn't go deep to get values of the interface. . It will iterate over each element of the slice. To declare a golang slice, use var keyword with variable name followed by []T where T denotes the type of elements that will be stored in the slice. For loop slice struct golang Code Example, “for loop slice struct golang” Code Answer. A, etc 100 times. 0. See the table to compare the properties of the nil and empty. A slice of structs is not equal to a slice of an interface the struct implements. I get the output: 0: argument_1 1: argument_2 // etc. Let's take a look at the example below to see how we can. It returns a slice of keys []K, so in the first line of the function body, the resulting slice is created. It's not a huge savings, probably not worth it, but you can fake iterating over numbers in a template without making an array of actual ints by using the empty struct: "pages": make([]struct{}, 16). If there is a match, we may stop the search and conclude that the element in present in the slice. If you want to iterate through an array or slice, you can use the for-range loop that we have already discussed earlier. Go to golang r/golang • Posted by West_Ad7170. g. Reverse (mySlice) and then use a regular For or For-each range. The range keyword is used like this: Syntax. The first is the index of the value in the slice, the second is a copy of the object. Summary. Line 20: We display the sum of the numbers in. 3 goals: 'dependency-check:check' concurrent: false. So you may simply convert a round number to big. [1,2,3,4] //First Iteration [5,6,7,8] //Second Iteration [9,10,11,12] //Third Iteration [13,14,15,] // Fourth Iteration. In general though, maps would normally be O (1) complexity, meaning that it takes a constant time to lookup any element in any part of the map by it’s key, whereas the complexity for a slice would be 0 (n), meaning that it can take as long as the number of elements in the slice to find a single element since you have to loop over each element. The other proposed solutions are also flawed; they don't work or they are inefficient. and lots more of these } type A struct { F string //. Then when we print the value of integers a second time, showing that they all now have a value of 0 through 9. In a slice composed of slices, if we use just one for loop, the program will output each internal list as an item:. Pass full slice range as parameter. // After the end of the range, the range function returns a zero date, // date. In this shot, we will learn how to iterate through a slice in Golang. Problem Solution: In this program, we will create a slice from an array of. An array holds a fixed number of elements, and it cannot grow or shrink. The sayHello function receives the names parameter as a slice. Annotations in the template refer to. Finally iterate once: for i:=0; i < len(s1); i ++ { fmt. View community ranking In the Top 1% of largest communities on Reddit. Floor (x) returns the greatest integer value less than or equal to x. Each character in a string is not stored as a byte, or int, but. Iterating through elements is often necessary when dealing with arrays, and the case is no different for a Golang array of structs. (map [string]interface {}) { // key == id, label, properties, etc } For getting the underlying value of an interface use type assertion. As mentioned by @LeoCorrea you could use a recursive function to iterate over a slice. Also, when asking questions you should provide a minimal reproducible example. In Java, we can iterate as below. From Effective Go: If you're looping over an array, slice, string, or map, or reading from a channel, a range clause can manage the loop. for i := 0; i < len(s); i++ {, without causing index-out-of-bounds errors. To understand better, let’s take a simple example, where we insert a bunch of entries on the map and scan across all of them. Also, each time you iterate on a map with range, you get a different order - another hint that there's no index concept in maps. The syntax to get the length of slice x is. The results: Gopher's Diner Breakfast Menu eggs 1. Defining a Slice. The for loop loops through a block of code a specified number of times. One method to iterate the slice in reverse order is to use a channel to reverse a slice without duplicating it. The range form of the for loop iterates over a slice or map. The range keyword works only on strings, array, slices and channels. Golang is an open source programming language used largely for server-side programming and is developed by Google. An array has a fixed size. Modified 4 years, 6 months ago. range is used to iterate over slices, arrays, and maps. for index, element := range x { //code } We can access the index and element during that iteration inside the for loop block. The code in this answer passes a slice value instead of passing a pointer to a slice. var x = map [string]map [string]string {}With the html/template, you cannot iterate over the fields in a struct. Golang: loop through fields of a struct modify them and and return the struct? 0 Using reflection to iterate over struct's struct members and calling a method on itGo slice tutorial shows how to work with slices in Golang. org, Go allows you to easily convert a string to a slice of runes and then iterate over that, just like you wanted to originally: runes := []rune ("Hello, 世界") for i := 0; i < len (runes) ; i++ { fmt. s = append (s, 2020, 2021) To find an element in a slice, you will need to iterate through the slice. This will give a sorted slice/list of keys of the map. For each iteration, the variable num takes on. After that, we can simply iterate over this slice and access the value from the key in the map. Since there is no int48 type in Go (i. From the language spec for the key type: The comparison operators == and != must be fully defined for operands of the key type; So most types can be used as a key type, however: Slice, map, and function values are not comparable. Name } The same for 2 other slices. For each number (int), we convert it, into. Step 4 − The print statement is executed using fmt. Capacity: The capacity represents the maximum size up. The counter is set from 0 or any other starting value as the. Writing generic code with type parameters. For example, for i, v := range array { //do something with i,v }. Golang doesn’t support any built-in functions to add items into a slice. The easiest way to do this is to simply interpret the bytes as a big-endian integer. In Go, in order to iterate over an array/slice, you would write something like this: for _, v := range arr { fmt. In go , the iteration order over a map is not guranteed to be reproducible. and lots of other stufff that's different from the other structs } type C struct { F string //. I’m looking to iterate through an interfaces keys. package main import "fmt" func num (a []string, i int) { if i >= len (a) { return } else { fmt. Println (line) } Run the code on the playground. For example I. 12 and later, maps are printed in key-sorted order to ease testing. range within range golang template. e. Split a string on , using func (s string) []string { return strings. Using the For Loop with Arrays, Slices, and Maps. Variables in Go (Golang) – Complete Guide. . For performing operations on arrays, the. While Arrays cannot be expanded or shrinked in size, Slices are dynamically sized. Using the for loop as a while loop is more common when you have a condition that isn't strictly based on the array or slice indices. Jeremy, a []string is not a subtype of []interface {}, so you can't call a func ( []interface {}) function with a []string or []int, etc. Not necessarily better, but the cleaner way to do this is by defining both the Slice LENGTH and CAPACITY like txs := make ( []Tx, 0, len (txMap)) // Defines the Slice capacity to match the Map elements count txs := make ( []Tx, 0, len (txMap)) for _, tx := range txMap { txs = append (txs, tx) }Check if Slice contains Specific Element. Notice that we only receive one value in our example for. For example if you want a slice where the first 10 elements are zeros, and then follows 1 and 2, it can be created like this: b := []uint{10: 1, 2} fmt. using the Int. To declare a golang slice, use var keyword with variable name followed by []T where T denotes the type of elements that will be stored in the slice. In this tutorial, we will learn the syntax of Floor () function, and how to use this function to find the floor value of a given number. Range can be used with an array, string, map or channels. 70. It enables us to contain contiguous data of any defined type which we can append to or iterate through. The code s = fmt. The c will be a rune that can contain more than one byte. arrayName is the variable name for this string array. Also, I am not sure if I can range over the interface slice of slice and store it in a csv file. Site. Access a map value using a variable key in a Go template. SetString() method), get its byte slice and reverse it. TL;DR package main import "fmt" func main { // slice of names names := [] string {"John Doe", "Lily Roy", "Roy Daniels"} // loop through every item in the `names` // slice using the `for` keyword // and the `range` operator. Iterate Go map get index. To cite the append() manual: «The variadic function append appends zero or more values x to s of type S,. Here's some easy way to get slice of the map-keys. 0. How familiar are you with the representation of different data structures and the concept of algorithmic complexity? Iterating over an array or slice is simple. Go range tutorial shows how to iterate over data structures in Golang. // If f returns false, range stops the iteration. Delicious! Listing the keys in a mapGo has a built-in range loop for iterating over slices, arrays, strings, maps and channels. Here's an example of how to iterate through the fields of a struct: package main import ( "fmt" "reflect" ) type Movie struct { Name string Year int } func main () { p := Movie {"The Dark Knight", 2008} val := reflect. 18. Println("Hello " + h. If you know that's your data structure, there's no reason to use reflection at all. Check the first element of the. Getting and setting length of arbitrary slice. Without that check, you risk a runtime panic. . 0. Embark on a journey through Golang slices, exploring their creation, manipulation, and efficient management in Go applications. 18 one can use Generics to tackle the issue. Reverse(. ExamplePractice Slices in Go are a flexible and efficient way to represent arrays, and they are often used in place of arrays because of their dynamic size and added features. The syntax to iterate over slice x using for loop is. Let’s. In Golang Range keyword is used in different kinds of data structures in order to iterates over elements. GoBytes (cArray unsafe. That's going to be less efficient than just iterating over the three slices separately, especially if they're quite large. In this article, we have discussed various ways of creating a for-loop. Messing with a slice (or map) while iterating it is dangerous. The following example uses range to iterate over a Go array. Simply excluding the initialization and postcondition, we can create another kind of for-loop which is the conditional for-loop. Reversing an array is fairly straightforward in Go, due to multiple return values. A, v. Step 2 − Create a function main and in that function create a string of which each character is iterated. select! { |val| val !~ /^foo_/ && val. From Effective Go: If you're looping over an array, slice, string, or map, or reading from a channel, a range clause can manage the loop. nums:= [] int {2, 3, 4} sum:= 0 for _, num:= range nums {sum += num} fmt. range on a map returns two values (received as the variables dish and price in our example), which are the key and value respectively. Iterate over the map by the sorted slice. Golang is a type-safe language and has a flexible and powerful. If you absolutely need it to work the way it is, you could use indexes instead of values returned by range. 1 Answer. Step 4 − The print statement is executed using fmt. While Arrays cannot be expanded or shrinked in size, Slices are dynamically sized. So, the way suggest is to hold the keys in a slice and sort that slice. When ranging over a slice, two values are returned for each iteration. Golang – Create empty Map; Golang – Map. That means the missing elements are still there but outside the bounds of the new slice. Iterate through a slice As arrays are under the hood modifications of arrays, we have a quite similar approach to iterating over slices in golang. Iterate on a golang array/slice without using for statement. Above method returns a channel over which ConcurrentMapItem items are being sent to and we can use the builtin range keyword to iterate over all items in the map. Using the Range Function in Golang to Iterate over the Channels. See 4 basic range loop (for-each) patterns. If the value of the length of the slice is zero, nothing is output; otherwise, dot (aka cursor) is set to the successive elements of the array, slice and Template is executed. The iterated list will be printed on the console using fmt. The following would also work: func multiple (slice []float64) { for index, value := range slice { slice [index] = value * 100 } } When you pass * []float64, the function gets a pointer to the slice. TrimSpace, strings.