Why can't I get the address of object in the map by it's index?

770 views
Skip to first unread message

hus...@163.com

unread,
Dec 7, 2014, 8:58:27 PM12/7/14
to golan...@googlegroups.com
Well, I want to test the object is save in the map by copying it or just a reference to the original object, so I did a test, but it seems Golang doesn't allow direct access to get the address of object in map by it's index. Code as follow:

package main

import "fmt"

type Student struct {
    name string
    age  int
}

func main() {
    s := Student{name: "charlie", age: 18}
    fmt.Printf("%p\n", &s)
    m := make(map[int]Student)
    m[0] = s
    fmt.Printf("%p\n", &m[0])  //I want to see if the object saved in the map is a reference to object or just a copy of it, but I got compile error here, showing "cannot take the address of m[0]"
}

Can someone explains it ?
1) why this operation is not allowed?
2) Is that some special restriction when using the map?

Matt Harden

unread,
Dec 7, 2014, 9:35:28 PM12/7/14
to hus...@163.com, golan...@googlegroups.com
You can't take the address of a map entry because the map may move entries around at any time. The map is not designed to work with mutable values.

Every time you use assignment, you are making a copy of the object. The compiler may be able to optimize the copy away in some cases, but in those cases you wouldn't be able to detect the fact within the code.

Here's how you can show that the object is copied, and not stored as a reference:

var i = 5
var m = make(map[int]int)
m[5] = i
i = 10
fmt.Printf("m[5] = %d, i = %d\n", m[5], d)

Just as it's true for an int, it will be true for any type or size of value.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jesse McNelis

unread,
Dec 7, 2014, 9:56:38 PM12/7/14
to hus...@163.com, golang-nuts
On Mon, Dec 8, 2014 at 12:58 PM, <hus...@163.com> wrote:
> Can someone explains it ?
>
> 1) why this operation is not allowed?

http://golang.org/ref/spec#Address_operators

> 2) Is that some special restriction when using the map?

There are many things that aren't addressable. Most of the reasoning
is about allowing flexibility and efficiency in implementation(maps)
or that the address of a thing doesn't have a reasonable
definition(constants, function calls).
Reply all
Reply to author
Forward
0 new messages