Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to use range in for loop to iterates over a slice in Go

2 Answers

0 votes
package main

import "fmt"

var sl = []int{1, 2, 3, 6, 7, 12, 16, 19, 20}

func main() {
	for i, val := range sl {
		fmt.Printf("al[%d] = %d\n", i, val)
	}
}


/*
run:

arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 6
arr[4] = 7
arr[5] = 12
arr[6] = 16
arr[7] = 19
arr[8] = 20

*/

 



answered Feb 28, 2020 by avibootz
0 votes
package main

import (
    "fmt"
    "math/rand"
)

func main() {
	sl := make([]int, 5)
	fmt.Println(sl)

	for i := range sl {
		sl[i] = rand.Intn(30)
	}
	for i, val := range sl {
		fmt.Printf("sl[%d] = %d\n", i, val)
	}
}


/*
run:

[0 0 0 0 0]
sl[0] = 11
sl[1] = 27
sl[2] = 17
sl[3] = 29
sl[4] = 1

*/

 



answered Feb 28, 2020 by avibootz

Related questions

2 answers 226 views
226 views asked Mar 15, 2020 by avibootz
6 answers 527 views
527 views asked Feb 22, 2020 by avibootz
1 answer 174 views
174 views asked Oct 24, 2020 by avibootz
1 answer 206 views
1 answer 171 views
1 answer 102 views
4 answers 237 views
237 views asked Jun 10, 2023 by avibootz
...