in Development

Google Go with a PHP background #1: Static types

As I come from the PHP world, I used to think that not having to worry about variable types was a good think. “It makes PHP dynamic!”, “It enables me to think about the application as a whole and not about stupid static types!”, “It is easy!” are often heard arguments. But as I grew as a developer I found out this is one of the “features” I started to hate most in PHP.

To be honest it is really hard to remember variables and their contents as you go, and in applications with 1000+ lines of code it is hard to keep track of all of them. One solution is of course to prefix all of the vars with their type (like $sVar is a string and $aVar is an array), but because it is so easy to change the content this gets easy to change. For some reason I started mixing up any random type with a boolean (if class variables are “empty” or “null” I used false) because it is so easy to check if it is set then. While checking user input you have to worry about if your app should think that “1″ is the same as 1, and false is the same as “false” (always use === in PHP). Well… I could go on for a while.

On to Go:

As Go is a statically typed language you have to define your types in front. The compiler simply fails if it does not recognize the type. At first this was hard for me, brought back the dreaded old days, but as I started using Go more often and in production environments this started to save me a lot of time. I realized it was just a bad habit I had to push. And because Go has the awesome := built in it is actually a breeze!

You could define a string variable like this in Go:

var Name string = "Martijn"

BUT, you could shorthand this to:

Name := "Martijn"

Go guesses its type. This is usually seen while working with package methods like:

results, err := getResults()

When you are starting in Go coming from php: This is gonna be a bitch. I cursed more than once about types not checking out, but it was all worth it. PHP and Go are as far apart in this as possible. But you hardly have to worry about variable content or user input validation type anymore.

Did I change my habits in PHP? To be honest, not that much :P

PS: Funny thing is that Hack (the Facebook PHP language) is said to just be PHP with types.

Martijn van Maasakkers

I'm a developer with over 10 years of experience writing code in PHP. Started developing in Go a while back and loving it!

Latest posts by Martijn van Maasakkers (see all)

Write a Comment

Comment

  • Related Content by Tag