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

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
}

2 Likes

Result should be something like this -
Widget_1
Widget_2
etc

2 Likes

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…

2 Likes

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

2 Likes

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.

2 Likes

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
}
}

2 Likes

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

2 Likes

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

1 Like

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