Recently I learned Go, but I didn’t have any projects to practice, so I forced myself: if I think of something interesting, I will see if I can use Go to achieve it, so I came up with this article.

The implementation process

Merge sort, merge sort, merge sort, merge sort, merge sort, merge sort, merge sort, merge sort, merge sort, merge sort At first, I used the usual routine, but I didn’t find it interesting. It was just “I feel like I’m writing in a language I know”.

The Go channel seemed to fit my bill in a way, and with the Goroutine thing in mind, I wondered if those two language features could be exploited as well.

Channel is a data structure that has a richer meaning in Go, but I basically use it as a queue. Goroutine is the same, I basically equate it to “user-mode threads” (both are awesome, but as an application layer developer, sometimes I don’t want to go too far and keep things simple).

Since I was just practicing, the API I came up with looked something like this:

Merge(ch1, ch2): outChan
Copy the code

Given two ordered channels, combine them into one ordered channel.

So my implementation is as follows:


func Merge(ch1 <-chan int, ch2 <-chan int) <-chan int {

    out := make(chan int)

    go funcV1, ok1 := <-ch1 v2, ok2 := <-ch2 // fetch datafor ok1 || ok2 {
            if! Ok2 | | (ok1 && v1 < = v2) {/ / to the minimum, to push out in out < - v1 v1, ok1 = < - ch1}else{out < -v2 v2, ok2 = <-ch2}} // Explicitly close(out)}() // after opening goroutine, the main thread continues to execute without blockingreturn out
}
Copy the code

The experience of using Go

The grammar borders on simplicity. But it doesn’t matter to me. I like it. Languages that don’t like too many syntactic features (syntactic sugar) are messy and too distracting. If every syntactic feature is orthogonal to each other, I’m all for it, but if multiple features are doing the same thing, it’s usually too burdensome for learners (Ruby) and not conducive to collaboration.

Compiled. Not much to say, almost is a necessary condition for me to learn a new language, early development efficiency may be slower, but the exchange is less bugs, especially for team collaboration, can reduce a lot of pain. (Python is great if you have a team of good people, but this condition is not always met. So use a compiled language :))