Hacker News new | ask | show | jobs
by polymathist 3847 days ago
There is a small discrepancy in the article:

> Go supports the := assignment operator, which works like this ... All this does is look at the return type of bar(), and set the type of foo to that.

This is a misunderstanding of the := operator and how type inference works in Go. If you look at the language spec (https://golang.org/ref/spec#Short_variable_declarations), you can see that the := operator is nothing more than a shorthand variable declaration.

x := "foo"

is shorthand for (and functionally equivalent to)

var x = "foo"

Type inference is orthogonal to the := operator and is a little more powerful than the author implies. For example, Go is able to infer the type of literals, including inferring the type of a numeric literal based on the presence of a decimal point or the symbol for the imaginary number, i (complex and imaginary numbers have native support). It can also infer the type when you assign a variable to an element in array, slice, or map or when you receive from a channel. Of course it can also infer types for values inside of a struct, map, slice, or array and for keys in maps. The only obvious difference I see between type inference in Go and Rust or Haskell is that in Go you must always define the return types for functions, but there may be more differences I am unaware of. See this playground example for a demo of a few different ways that types can be inferred in Go: http://play.golang.org/p/8ep340vLky.

(edit: formatting)