0

Why can't I do it like this in Go?

func do(m1 map[int]string) {
    var m map[int]string = make(map[int]string)
    *m1 = &m;
}

I have m1 map, which means I can now it's reference? How to assign a new object to that memory pointer?

1
  • 1
    m1 is not a pointer type, so you can not use * to access its value. Commented Sep 4 at 15:08

1 Answer 1

2

m1 is a map, and it is passed by value to the function do. That is, where the function is called, a copy of another map variable is passed. The fact that a map is a pointer type is irrelevant here. A copy of that pointer is passed.

If you want to change the map at the call site, you have to pass it as pointer:

func do(m1 *map[int]string) {
    var m map[int]string = make(map[int]string)
    *m1 = m;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.