Последние 15 лет моей карьеры большая часть моей работы была на Java, C ++ или Objective-C для приложений IOS. В прошлом году я много работал в Go, и многие мои коллеги по Java спрашивали меня, что делает Go таким замечательным в работе. Вот 6 причин высокого уровня, почему я люблю Go.
1. Быстрый процесс разработки
Go — чрезвычайно простой язык для изучения. Go — это C-подобный язык, он выглядит как C и позволяет ссылаться на C-библиотеки. Если вы изучаете Го, я предлагаю вам пройти Тур Го, который можно сделать за несколько часов. Еще одна хорошая ссылка — это чтение Pointers in Go
Go очень быстро компилируется. Вы можете собрать 5 МБ, статически типизированный двоичный файл в секунду или меньше. Это произошло из-за того, что Роб Пайк , Кен Томпсон и Роберт Гриземер начали теоретизировать о Go, ожидая создания большого C ++. Это началось на доске в 2007 году и вскоре превратилось в спецификацию.
Пример: Hello World
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello World")
}
Go has an extensive standard library that offers developers a lot of flexibility. One feature that stood out to me when I was initially learning Go was the ability to quickly build a web server in Go.
Lets redo our Hello World example above so you can access it via a web browser.
Example 2: Hello World through HTTP
helloweb.go
and copy and paste the following code:package main
import (
"io"
"net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello world!")
}
func main() {
http.HandleFunc("/", hello)
http.ListenAndServe(":8000", nil)
}
- In terminal, execute the command
go run helloweb.go
. - Open your browser to
http://localhost:8000
and you will seeHello world!
appear.
Wasn’t that easy? The example above listens on port 8000 and directs requests to the hello function which outputs “Hello world!”
2. Hasta la Vista Dependencies
When you compile in Go the end result is a statically linked binary that runs natively on the target platform. This means you no longer need to install Java (VM & Dependencies), Python, Ruby + Gems, just to run your program.
Go supports seamless cross compilation for Windows, OS X, Linux, and BSD. I’m a Mac user and found it very cool that I could cross compile a Windows binary for my windows based engineers.
Here’s a few examples of compiling a Windows and Linux binary on a Mac.
Windows:
GOOS=windows GOARCH=386 go build -o appname.exe
Linux:
GOOS=linux GOARCH=amd64 go build -o appname.linux
3. One Format Fits All
Code reviews are a best practice that every quality team should be doing. When reviewing code you’re also having to spend time to insure the formatting is meeting the teams guidelines. This wastes time when really we should be spending time on the code and mentoring.
GoFmt solves this by formatting your source code into the standard format. Time is saved and arguments of tabs vs. spaces are history. There is one universal format and this is GoFmt.
4. Concurrency Not Parallelism
Go was designed with concurrency first. Go’s approach to concurrency originates in Hoare’s Communicating Sequential Processes (CSP).
The keyword go
starts a go-routine which is a lightweight thread essentially. When you execute a go-routine there is no need to worry about which processor it runs on. Shared values between routines are passed around on channels. You epoll those channels using the select
keyword. Only one goroutine has access to the value at any given time which eliminates race conditions.
I could write a whole post about go-routines but instead you should watch this great video by Rob Pike, entitled Concurrency is not Parallelism.
Example: Go-Routine Fibonacci sequence
package main
import "fmt"
func fibonacci() chan int {
c := make(chan int)
go func() {
for i, j := 0, 1; ; i, j = i+j,i {
c <- i
}
}()
return c
}
func main() {
c := fibonacci()
for n := 0; n < 12 ; n++ {
fmt.Printf("%d ", <- c)
}
}
The example above starts a go-routine and returns a channel to the fibonacci sequence. Every iteration reads a number from the channel c
. Try the above example out in the Go Playground.
5. Built in Testing
In Go, testing is built into the language. Name a file with the suffix of _test.go and it’ll only build within the test lifecycle. You run tests by executing go test
in the directory. Go also allows you to have built-in benchmarks that are controlled by the go tool allowing your test to run enough iterations to get an impactful result, displayed in operations per second.
6. Go Docs
HTML (aka Go Doc) documentation is built into Go. You no longer need to worry about annotated comments or other directives to produce nicely formatted docs. Plaintext comments are turned into very simplistic, modern based documentation.