Trying to make a counter that increments a number once every loop and add it to a string ("Widget_number that adds with every loop"), from a struct


(Justin) #1
for i := 0; i < 10; i++ {
	//v := counter + 1
	producer1 := widget{
		"Widget_",
		time.Now(),
	}
	time.Sleep(time.Second * 5)
	p <- producer1
}

Heres the struct if you need, but i aint supposed to change the type -
type widget struct {
Label string
Time time.Time
}


(Justin) #2

Result should be something like this -
Widget_1
Widget_2
etc


(Norbert Melzer) #3

I’m not sure whether or not I really understand what you are trying to do…

But just incrementing some number ang printing it is quite easy, especially as you are already using a for with incrementing counter…

for i := 0; i < 10; i++ {
  fmt.Println("widget_%d", i)
}

Not sure what you are using channels for or what that struct shall do…


(Justin) #4

Trying to say that im not incrementing the number in a fmt.Println statement, but incrementing the number, and concatenating it to a string which is label (widget_#) need the number where the # is

producer1 := widget{
	"Label":"Widget_#",
	"time":time.Now(),
}
time.Sleep(time.Second * 5)
p <- producer1

}
And in every loop i print out the struct using channel, the number will be adding up… Hope you understand


(Norbert Melzer) #5

So then use fmt.Sprintf to create your label if you do not want to print directly but need it in a string. Alternatively you can use strconv packages functions and concatenate the strings.


(Justin) #6

Thanks, ive gotten pretty far. Now the issues that my number doesnt get incremented in the loops
func send(p chan<- widget) {
counter := 0
for i := 0; i < 10; i++ {
v := counter
v++
const label = “Widget_”
producer1 := widget{
fmt.Sprintf("%s %d", label, v),
time.Now(),
}
time.Sleep(time.Second)
p <- producer1
}
}


(Norbert Melzer) #7

You reset the v back you counters value of 0. Why not just use i?


(Justin) #8

Thanks a lot.Working now. I’ve got a lot to learn. Hopefully i don’t breakdown