Variables – Getting Help

Greetings,
Below you can find a piece of code (which doesn’t work). My intention was to draw a number (1,2 or 3), then assign a text value to each number and then print it 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’s the catch? It says “b” is declared but not used. I found out that “b” was declared inside the “switch” function, so it stays within its bounds. But I want to use “b” outside the “switch” function (so it can print 10 lines of one of three colors). Is there a way to make the variable “global” somehow. Even if they were declared inside something else?


Leave a Comment