Accessing a channel from a different goroutine


I currently have the following code:

package main

import (

var channel = make(chan []float32, 1)

func main() {
    aMap := initMap()

    for key := range aMap {
        fmt.Print("the iteration number is: ", key)

        theSlice := aMap[key]
        channel <- theSlice
        go transition(channel)
        time.Sleep(2 * time.Second)


func transition(channel chan []float32) {
    newSlice := make([]float32,5)
    newSlice = <- channel

    //need to retrieve the last element of the other slice and put it on this newSlice

func initMap() map[int][]float32 {
    aMap := make(map[int][]float32)
    for i := 0; i < 2; i++ {
        aMap[i] = []float32{rand.Float32(), rand.Float32(), rand.Float32(), rand.Float32(), rand.Float32()}
    return aMap

We have a map with two slices and what i’m trying to do is take the last element of slice1 and make it the last element of slice2 and vice versa.

I’m actually working on a bigger project that involves simulating the division and differentiation of cells. Since its a simulation, all the divisions and differentiations are going on at the same time. The issue is with differentiation, where a cell of typeA is transformed into a cell of typeB. Each type of cell is stored in a different data structure and i figured i could use one channel for each different data structure and use the channels to change the data concurrently.

Hope this makes sense. Any suggestions?


EDIT: it seems what i’m asking isn’t clear. My question for the example above is, how would i go about inter-changing the last elements of each of the two slices concurrently?


Channels are two way, and are about communication, not sharing memory. So perhaps instead of sending the entire slice, just sending the last item in each slice one way down the channel and then sending the second value back the other way.

  func main() {

    // send only the last item
    theSlice := aMap[key]
    channel <- theSlice[len(theSlice)-1]
    // waiting for the response
    theSlice[len(theSlice)-1] = <- channel

  func transition(channel chan []float32) {
    newSlice := make([]float32,5)
    channel <- newSlice[len(newSlice)-1]
    newSlice[len(newSlice)-1] = <- channel

The above code does assume that the channel declaration has been changed away from a slice to just a float32 :

 var channel = make(chan float32, 1)

Answered By – miltonb

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.