pointers - Go array for method -


can use array , pointer go methods?

i have following code:

var array = [3]string{"a", "b", "c"} type arraytypept *[3]string func (m *arraytypept) change() { m[1] = "w" } func main() {     (arraytypept(&array)).changearray4() } 

but code: http://play.golang.org/p/mxdehma9wk

give me error of:

invalid receiver type *arraytypept (arraytypept pointer type) invalid operation: m[1] (type *arraytypept not support indexing) arraytypept(&array).changearray4 undefined (type arraytypept has no field or method changearray4) 

i same error when try slice. why cannot in method?

the receiver type of method cannot pointer pointer, wrote:

func (m *arraytypept) change() { m[1] = "w" } 

arraytypept pointer *[3]string. quoting language specification:

[the receiver] type must of form t or *t (possibly using parentheses) t type name. type denoted t called receiver base type; it must not pointer or interface type , must declared in same package method.

your 2nd error ("type *arraytypept not support indexing") result of (m pointer pointer, that's why can't index it; if pointer array or slice, pointer indirection automatic).

your 3rd error typo, declared method named change() , not changearray4().

so should name non-pointer array type:

type arraytype [3]string 

and can declare array using directly type:

var array = arraytype{"a", "b", "c"} 

and can call change() method:

array.change() 

the address of array taken automatically (because change() method has pointer receiver array variable not pointer).

try on go playground.

notes / alternatives

if want array variable explicitly [3]string, still make work converting arraytype, setting variable, , change() can called on (because being variable address can taken - while address of conversion arraytype(arr) cannot):

arr2 := [3]string{"a", "b", "c"} arr3 := arraytype(arr2) arr3.change() 

or if declare variable pointer type [3]string, save required additional variable (which required able take address):

arr4 := new([3]string) *arr4 = [3]string{"a", "b", "c"} ((*arraytype)(arr4)).change() 

try these variants on go playground.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -