-rob
type Struct struct {
a []int
}
func New(sz int) *Struct {
return &Struct{a: make([]int, 0)}
--
Scott Lawrence
Use a pointer receiver:
func (neur *Neuron) Init(weights []float64) *Neuron { ...; return neur }
The receiver is just like any parameter (except for a couple special
case rules). What you see inside the function is a copy of what the
caller had. By making the receiver a pointer, you get a copy of a
*pointer* to Neuron, which means you can alter the caller's Neuron
object. Otherwise, the caller's Neuron is unaltered, so their
myInstance.Weights is still nil.
The common Go idiom is to have the Init method return the receiver, so
that people can do `neur := new(Neuron).Init(...)`. This gives you
more flexibility in how you can initialize the value.
Alshere's a built-in copy function, copy(dst, src), so you don't need
the loop. Plus, you can declare use a slice literal []float64{ 5.1,
42.0, 3e3 } rather than slicing an array literal.
I would highly recommend reading the spec:
http://golang.org/doc/go_spec.html It isn't long, and from it you can
learn everything in the language (it's not much to remember, Go is a
fairly simple yet powerful language).
It's even more idiomatic to have a function called New that returns the object.
After calling myInstance.Init([...]float64{1,2,3,4}[:])
// Copy the values in the passed array to the new one
for i,v := range weights {
neur.Weights[i] = v
}