Go (0)
14-Nov-09
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);
}
m := new(map[string]int); m["one"] = 1;
m1 := new(map[string]int); *m1 = make(map[string]int); (*m1)["one"]=1;
m1 := make(map[string]int); pm1 := &m1;
- 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.
- ‘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.
