Settings

Theme

Python to Go Cheatsheet

353.solutions

34 points by tebeka 8 years ago · 7 comments

Reader

posedge 8 years ago

My god is go a cumbersome language. I get why the explicitly returned errors are a good thing but the complexity for parsing json surprises me

  • nytopop 8 years ago

    That's an artifact of it being statically typed. The data type to unmarshal into / marshal from needs to be defined somewhere. The extra stuff apart from error handling isn't required if you use a more generic type like `map[string]interface{}`.

  • ben_jones 8 years ago

    What?

    // example for unmarshalling an http request to JSON

    contents, err := ioutil.Readall(req.Body)

    if err != nil { return err }

    req.Body.Close()

    user := new(User)

    if err := json.Unmarshal(contents, user); err != nil { return nil }

    // do whatever you want with 'user'

    • Majora320 8 years ago

      Why do you have to call `req.Body.Close()`? Does Go not have RAII?

      Does Go have something analogous to Rust's `try!` or `?` operator, which would turn it into (pseudocode):

          contents, err := try!(ioutil.Readall(req.Body))
      Or:

          contents, err := ioutil.Readall(req.Body)?
      If not, why not?

      (I don't know Go)

      • candiodari 8 years ago

        No garbage collected language will ever have RAII, the features conflict. Go does not have RAII, but tries to fix it with "defer" [1].

        As for why not, you'd have to ask the Go team. But my guess would be that as a general rule, Go does not have language feature X. It's a very, very basic language deliberately lacking pretty much every modern language feature you can think of. The pro/con is that programming in Go is very delibarete. Go programs will only ever do what you explicitly make them do, to an almost ridiculous extent. If a Go program knows how to sort a list of customers, it takes 20 lines of code to make it aware of how to sort any other record type. Especially operations minded people this is a big plus.

        [1] https://blog.golang.org/defer-panic-and-recover

    • jimsmart 8 years ago

      Perhaps worth pointing out, pedantically, that really only the final two lines are the JSON handling — the first three lines here are reading/handling the input stream (HTTP).

mzzter 8 years ago

For those fluent in Go first, this is good as a quick Go to Python reference too. Though good as an initial quickstart, this invites programming in Go using a Python-style and vice versa. Glad that there’s at least a section on goroutines and chan.

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection