Reputation: 10846
I don't understand why the pointer s
is nil
even after the input()
method initialised it. Any idea?
package main
import "fmt"
type ps string
func(s *ps)input(){
x := ps("a")
s = &x
}
func(s *ps)output(){
}
func main() {
var v *ps
v.input()
if v == nil{
fmt.Println("v shouldn't be nil")
}
}
Playground http://play.golang.org/p/jU2hoMP7TS
Upvotes: 2
Views: 765
Reputation: 30057
You need two things--main
needs to allocate space for a ps
that input
can write into, which you can do by replacing var v *ps
with v := new(ps)
. The string will be ""
, but it doesn't matter what it is, just that there's space set aside in memory for a string header that input
can write to. As Momer said, otherwise the pointer's nil
and your program panics trying to dereference it.
And in order to assign through a pointer, input
needs to use *s = x
. Since *s
is, informally, "get what s
points to", you can read that as "change what s
points to to x
". Usually the automatic ref/deref behavior around the dot operator and method calls saves you from that, but when you assign through a pointer type or do other operations (arithmetic, indexing, etc.) the dereference needs to be there in the code.
Upvotes: 1
Reputation: 2248
v value (0) is passed into v.input. Passed value is stored in a local variable s. s value is modified. No one is saving new s value back into v.
If you want something modified in your function, you must pass pointer to the value. (or reference for slices, maps and so on).
If you want to change pointer value, you should pass pointer to your pointer.
Alex
Upvotes: 0