slice copying over channel

2,367 views
Skip to first unread message

Abhijit Kadam

unread,
Jun 24, 2014, 4:03:39 AM6/24/14
to golan...@googlegroups.com
From one routine if I create slice and pass it to other routine through channel then before the other routine reads the slice data (array slice is pointed to), if I set the slice to another location then will the other routine still read the old slice data always consistently? I assume it should as I am copying the slice, so it is copy of the reference which points to the array data.


datach := make(chan []string)

routine 1:
for {
// create a slice
str := make([]string,0) 

//fill it with values
str = append(str, "value " + strconv.Itoa(i))

//Send the slice to channel so that other routine reads
datach <- str
//***continue the loop and the same slice reference will point to new array location
}

Another routine 2:
for {
strc := <-datach
}

once the str is copied over channel then is it safe to point to another location without the previous data not getting garbage collected or overwritten?

roger peppe

unread,
Jun 24, 2014, 5:00:41 AM6/24/14
to Abhijit Kadam, golang-nuts
You're creating the slice each time around the loop,
so you will be ok, assuming you don't modify
the contents of the slice after sending it.

But in general, passing a slice over
a channel does not copy the entire slice - it passes a
reference to the items in the slice.
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Matt Harden

unread,
Jun 26, 2014, 2:16:35 PM6/26/14
to roger peppe, Abhijit Kadam, golang-nuts
More pedantically, it does copy the slice, but the slice is internally just a pointer, length and capacity. Just as copying a pointer doesn't copy the data pointed to, copying a slice doesn't copy the data pointed to either.

Paweł Smorczewski

unread,
Feb 22, 2023, 10:14:51 AM2/22/23
to golang-nuts
Mat Harden, its not pedantically, its precisely. I think being precise with terms and words is very important especialy in IT, where new technologies are emerging everyday. IT world has already too much confusion about wording, definitions and so on. Giving precise answer with proper context speeds up learning process, especially for newcomers. I think it's worth to keep that in mind, in the end by answering someone's question we want to be helpful not make someone confused. 
Reply all
Reply to author
Forward
0 new messages