Go (0)

Go is google’s new language. I am at the very first step learning it. It’s said Go is a ‘when Python meets C++’ language, sadly I only know a little C++, nothing about Python. It has been a tough time for me to understand something inside. The first obstacle is the keyword ‘new’.

‘new’ in Go doesn’t have the same semantic as in C++. For value types, it allocates the  memory and returns the pointer to that piece of memory (in heap) – this is familiar, for example:

type T struct {a, b int}
func main() {
    t := new(T);
    fmt.Printf("t.a=%d, t.b=%d\n", t.a, t.b);
}
However, if you want to use something which should be constructed before use,  the keyword ‘new’ doesn’t really work as expected. Try this:
m := new(map[string]int);
m["one"] = 1;
It seems nothing is wrong.  But actually if you run it,  ’SIGSEGV: segmentation violation’. Why?
The reason is that ‘new’ here only declares that m is a pointer to a map[string]int, and initialize m to an allocated piece of memory in heap. But that memory, is initialize to zero.  (in C++, the constructor is also invoked to really initialize the memory but Go type doesn’t have constructor/destructor).  So the pointer is ready, but memory is not.  Then, how should we (if really want) use new with map?
m1 := new(map[string]int);
*m1 = make(map[string]int);
(*m1)["one"]=1;
This is the answer. However, you can doesn’t mean you have to or should.  As it is a reference, there is no point to use a pointer anywhere – functions taking map as parameter makes no copy. If when necessary, & will get the address of a map.
m1 := make(map[string]int);
pm1 := &m1;
What’s behind these? To understand this, remember two things.
  1. Go doesn’t have constructor. So ‘new’ will allocate memory, initialize it as zero. For those non-zero-value-is-useful type, explicit initialization is mandatory.
  2. ‘make’ is also used to allocate memory. But it applies only to map and channel which must be initialized before use, and array which is ready to be sliced.
Why Go is designed like this? I don’t know…
Reference:

‘Me’ at Time Square

Billboard

Story here. I am the second from left in the front row.

It’s final

http://www.topcoder.com/news/2009/04/13/announcing-tco09-champions-assistant-and-saarixx/

*assistant is the 2009 TopCoder Open Component Development Champion!*

See his road to the top here.