Make the structure "long-range"?

type Friend struct { name string age int } type Friends struct { friends []Friend } 

I would like to make Friends range-able, which means that if I have a my_friends variable of type Friends , I can loop, although this is with:

 for i, friend := range my_friends { // bla bla } 

is it possible in go?

+6
source share
3 answers

Do friends have a structure? Otherwise just

 type Friends []Friend 
+11
source

Beware . As deft_code is mentioned, this code leaks out the channel and goroutine when the loop breaks. Do not use this as a general template.


There is no way in go to make an arbitrary type compatible with range , since range only supports slices, arrays, channels, and maps.

You can iterate through the channels using range , which is useful if you want to iterate over dynamically generated data without the need to use a slice or an array.

For instance:

 func Iter() chan *Friend { c := make(chan *Friend) go func() { for i:=0; i < 10; i++ { c <- newFriend() } close(c) }() return c } func main() { // Iterate for friend := range Iter() { fmt.Println("A friend:", friend) } } 

What is the closest thing you need to do to make something "affordable."

So, it’s common practice to define an Iter() method or something similar by type and go to range .

See the specification for further reading on range .

+9
source

For instance,

 var my_friends Friends for i, friend := range my_friends.friends { // bla bla } 
-1
source

Source: https://habr.com/ru/post/927733/


All Articles