My way from Python to Go - sharing tips and resources



    From a translator: translated for you an article by Ilad Leev about the transition from Python to Go . The article will be useful not only to novice programmers, but also to anyone who is interested in Go in any way.

    I like Python. This language has been my favorite for the past five years. He is friendly, efficient, and easy to learn. It is used for almost everything: from creating simple scripts and web development to data visualization and machine learning. The

    gradual "ripening" of Go, the vast community and the fact that more and more companies are adopting this language after successful tests made me pay attention to it and delve into the literature. But this post is not about which is better - Python or Go: online comparisons are huge. In my opinion, it all depends on the application. I’m going to talk about why I chose Go, giving some tips and links to useful resources for everyone interested in the topic.

    Skillbox recommends: A hands-on course Python developer from scratch .

    We remind you: for all readers of “Habr” - a discount of 10,000 rubles when registering for any Skillbox course using the “Habr” promo code.




    Observations


    The first thing I did at the beginning of the journey was to study the excellent official Tour Of Go tutorial . It gives an understanding of the syntax of the language.

    In order to improve my knowledge, I also read the book “ Go for Python Programmers ”, which allowed me to proceed to the next stage - trial and error.

    I took the usual functions that I used in Python (serializing JSON or working with HTTP calls), and tried to write them in Go. Thanks to such a visual comparison, I was able to identify key differences between languages.

    Project Layout

    First of all, Python does not require a specific directory hierarchy, while Go does.

    Go uses a “standard” layout that is a bit more complicated and requires more work. On the other hand, as a result, we get a well-structured code base, which uses a modular structure, and when expanding the project, the code remains strictly ordered.

    The official “ How to Write Go Code ” tutorial explains how to organize your work.

    Static strong typing

    Go is statically typed, and it will make you feel at ease for those who are used to dynamically typed languages ​​like Python and Ruby.

    There is no doubt that dynamic languages ​​are more prone to errors; the developer requires more effort in checking the input data. An example is a function that calculates the sum of two integers. If you pass a string to a function (which is not so rare), this will lead to a TypeError error.

    This cannot happen in Go, because here you need to declare a type for each variable and function and what type of variable the function will return.

    At first it was annoying: it seemed to me that this Go feature was slowing down, but then it came to understand that in fact, declaring everything saves time and reduces the likelihood of errors.

    Native concurrency

    Go has native concurrency support using routines and pipes — this is convenient.

    The concept of channels at first seems a bit confusing. However, over time, it becomes more understandable, and you begin to enjoy new opportunities, actively working with them.

    Here is a visualization of everything said by Ivan Danilyuk .
    package main
    func main() {
        // create new channel of type int
        ch := make(chan int)
    // start new anonymous goroutine
        go func() {
            // send 42 to channel
            ch <- 42
        }()
        // read from channel
        <-ch
    }



    More examples here and here .

    Working with JSON

    Well, json.loads () is no more. Everything is simple in Python: we use json.loads and there are no problems.

    But in Go, a statically typed language, this operation becomes more complicated.

    Here, when using JSON, everything is predefined. Any field that does not fit into the given structure will be ignored, and that’s good. This can be thought of as a pre-agreed protocol between the two parties. The data that you received in JSON must be expected, and the fields and JSON types are “agreed” by both parties.
    {
      “first”: “Elad”,
      “last”: “Leev”,
      “location”:”IL”,
      “id”: “93”
    }

    type AccountData struct {
     First    string `json:"first"`
     Last     string `json:"last"`
     Location string `json:"location"`
     ID       string `json:"id"`
    }

    Of course, you can deserialize JSON without structures, but whenever possible this should be avoided and the static nature of the language should be taken into account.

    JSON decoding on GO is best explained in this post or here .

    Lazy to convert your JSON into a Go-structure? No problem, this tool will do everything for you .

    Clean Code

    The Go compiler will always try to keep your code “clean.” It considers unused variables a compilation error. Go uses a unique approach that allows the system to solve most formatting problems. So, Go will run the gofmt program when saving or compiling and independently correct the formatting.

    Do you care about variables? Okay Just use _ (underscore) and assign it to an empty id.

    The mastrid tutorial for this part of working with the language is the information from “ Effective Go ”.

    Finding the right library and frameworks

    I used Python frameworks and libraries like Flask, Jinja2, Requests, and even Kazoo, so I was afraid that I would not find anything suitable for Go.

    But the community has already solved these problems: the language has its own unique libraries that allow you to completely forget about what you used earlier.

    Here are my favorites.

    Python Requests => net / http

    net / http provides a convenient and easy-to-use implementation of the HTTP client and server.

    Flask + Jinja2 => Gin

    Gin is an HTTP web framework with a very simple API: path parameters, downloadable files, group routing (/ api / v1, / api / v2), custom log formats serving static files, HTML rendering and a really powerful custom middleware.
    Rate this benchmark.

    CLI Creation => Cobra

    Cobra is a library for creating powerful CLI applications, as well as a program for generating applications and batch files.
    Cobra is used in many large Go projects, including Kubernetes, etcd, and OpenShift.

    Here are some more libraries that I highly recommend: Viper , Gonfig, and this awesome list is Awesome-Go .

    Other useful resources


    [1] Francesc Campoy  - You definitely need to rate this YouTube channel and GitHub profile .

    [2] GopherCon - video .

    [3] Go Web Examples .

    [4] Golang Weekly , Gopher Academy , Golang News - Twitter accounts.

    To summarize


    As a regular Python user for five years, I was afraid that going to Go would be painful.

    But no: there is the groundwork of the Go community, which expands and complements the capabilities of the language, as well as various useful resources that will help you with the transition.

    Go is growing fast, and I hope that Google can make it the main language for writing cloud applications and infrastructure.

    Join now!



    Skillbox recommends:


    Also popular now: