Hey I'm new to Go syntax. How would I use this function? The part that is throwing me is the pointer at the beginning of the function declaration?
func (p *Pointer) FunctionName(arg string) error {
dec := json.NewDecoder(strings.NewReader(arg))
err := dec.Decode(&p)
return err
}
FunctionName
is a method on *Pointer
.
If you are asking how to use the code on arbitrary types and not just a *Pointer
, then write it as a function:
func FunctionName(v interface{}, arg string) error {
dec := json.NewDecoder(strings.NewReader(arg))
err := dec.Decode(v)
return err
}
Assuming that p
is a variable of type *Pointer
, then call it like this:
FunctionName(p, "{... JSON text here }")
This is a method definition. The way to use it is
var p Pointer
/* or */
p := new(Pointer)
p.FunctionName(arg)
In Go struct types can contain methods, and that is what you have here. Say I have the following code:
type Foo struct {
Something string
}
func (f * Foo) PrintSomething() {
fmt.Println(f.Something)
}
I cannot invoke PrintSomething
directly, I must invoke it by using a variable of type Foo
. Example:
f := Foo{
Something: "Something",
}
f.PrintSomething()