2009/11/14 micheles <
michele....@gmail.com>:
By "type assertion" I presume you mean the (func() int) conversion the
the third-last line:
fmt.Printf("%d\n", a.At(i).(func() int)())
You can't remove it yet, because go does not have generics yet.
http://golang.org/doc/go_lang_faq.html#generics
As for making it shorter, it certainly can be shorter, but I'm not
sure exactly what you're trying to do. For example,
a := make_vector(func() int { return 0 }, N);
sets all three elements of the vector to be the same "always return
zero" function. But in the very next bit of code
for i := 0; i < N; i++ {
a.Set(i, func() int { return i })
}
You're setting all three elements of that very same vector, i.e.
you're overwriting what you just did. So you could make your code
shorter by removing the make_vector call and just having
a := vec.New(N);
Also, if you were wondering, the program prints "3\n3\n3\n" because
the functions you set all close over the same variable i (the i of the
first for loop in main(), which is not the same i as the one in the
second for loop). If you want the program to print "0\n1\n2\n" then
replace the first for loop by
for i := 0; i < N; i++ {
j := i;
a.Set(i, func() int { return j })
}
so that the anonymous function (i.e. a closure) closes over a
different j each time.
Final nit: for a local variable, I'd use n rather than N.