Original post

My code is to sort a slice of numbers by breaking down the slice into 4 subslices and then each goroutine would sort one subslice. The user will input the slice of numbers. But my code executes before the input is given, I know goroutines are meant for that, to not waste time and execute in the meantime. But is there a way to wait until the input is given and then the goroutines are executed?

Here’s my code:

    package main 
      
    import ( 
        "fmt"
        "sync"

    )


    func main() { 
        
        var ele int
        var lng int
        var waitGroup sync.WaitGroup
        num_slice := make([]int,0,3)
        fmt.Println("How many elements do you want in your slice? ")
        fmt.Scan(lng)


        
        fmt.Println("Enter a slice of 10 elements:")
        
        for m := 0; m < lng; m++{
            fmt.Scan(&ele)

            num_slice = append(num_slice, ele)
            
           
        }
        fmt.Println(num_slice)
        
        s:= make(chan int)

        subSlice := lng / 4
        slice1 := num_slice[ :subSlice]
        slice2 := num_slice[subSlice : 2*(subSlice)]
        slice3 := num_slice[2*(subSlice) : 3*(subSlice)]
        slice4 := num_slice[3*(subSlice): ]

        
            
        waitGroup.Add(4)

        go sortedSub(slice1, s)
            
        waitGroup.Done()

        go sortedSub(slice2, s)
            
        waitGroup.Done()

        go sortedSub(slice3, s)
            
        waitGroup.Done()

        go sortedSub(slice4, s)
            
        waitGroup.Done()

        waitGroup.Wait()
        

        fmt.Println("The final:")

        fmt.Println(s)
        fmt.Println(slice1)
        fmt.Println(slice2)
        fmt.Println(slice3)
        fmt.Println(slice4)

    } 




    func sortedSub(sl []int, s chan int){
        el := 0
        fmt.Println("subslice:", sl)
        Sort(sl)
        for _, v := range sl {
            el=v
            s <- el
        }  
    }

    func Sort(sl []int) {
        for i := 0; i < len(sl); i++ {
            for j := 0; j < len(sl)-1; j++ {
                if sl[j] > sl[j+1] {
                    Swap(sl, j)
                }
            }
        }
    }

    func Swap(sl []int, position int) {
        temp := sl[position+1]
        sl[position+1] = sl[position]
        sl[position] = temp
    }

output:
C:UsersHOME PCDesktopGo>sort4
How many elements do you want in your slice?
Enter a slice of 10 elements:
[]
The final:
0xc00003c0c0
[]
[]
[]
[]

C:UsersHOME PCDesktopGo>