Variables' range

Hi all,
below you can find a piece of code (that doesn’t work). My intention was to draw a number (1,2 or 3), then assign the text value to each number and then print it out 10 times.

package main
import (
	"fmt"
	"math/rand"
	"time"
)
func main() {

var iteration = 0


for iteration < 10 {					//repeat all 10 times
			
			
			
		rand.Seed(time.Now().UnixNano())	//start source
		var a = rand.Intn(4-1)+1		//draw 1-3 

		switch a {				//assign text value for "b"			
			case 1: 
			var b = "green"
			case 2: 
			var b = "yellow"
			case 3: 
			var b = "red"
			}			
	fmt.Println(b)				//print out b (green or yellow or red)	
	iteration++			
	}
}

Where is the catch? It says that “b” is declared but not used. I figured out that “b” was declared inside “switch” function, so it stays in it’s range. But I’d like to use “b” outside the “switch” function (so It can print 10 lines of one of three colours). Is there a way to somehow make the variables “global”. even If they were declared inside something else?

Hi, you can just define your b variable out of your switch scope with var b string.
One more additional thing is that you have to move seed set function out of the loop to get pseudo random value each time.

package main
import (
	"fmt"
	"math/rand"
	"time"
)
func main() {

var iteration = 0

rand.Seed(time.Now().UnixNano())	//start source

for iteration < 10 {					//repeat all 10 times
		var a = rand.Intn(4-1)+1		//draw 1-3 

                var b string

		switch a {				//assign text value for "b"			
			case 1: 
			b = "green"
			case 2: 
			b = "yellow"
			case 3: 
			b = "red"
			}			
	fmt.Println(b)				//print out b (green or yellow or red)	
	iteration++			
	}
}

Unrelated, but it is more idiomatic and less error prone to use the variant of for with three parts to keep the loop control in one place. A Tour of Go

Thanks guys! I read somewhere that Go complier automatically identifies the type of value once the variable is set, so I thought that “var b string” is not required.

You are thinking of the := operator, which is simply a short cut for var varName varType = someValue where varType is inferred from someValue. It combines declaration and assignment. You still need to declare the variable by either var or := in the scope where it is to be accessed.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.