I am trying to create a map of addresses of objects that I create with the time at which it is allocated. The key is the address returned by the call to new()
. How do I get the address returned by new()
?
type T struct{a, b int }
func main(){
var t int64 = time.Nanoseconds()
memmap := make(map[uint8]int64)
fmt.Printf("%d
", t)
var ptr *T = new(T)
ptr.a = 1
ptr.b = 2
fmt.Printf("%d %d %p %T
", ptr.a, ptr.b, ptr, ptr)
//memmap[ptr] = t //gives error
//var temp uint8 = ptr//gives error
}
Please tell me what should be the type of the key field in the map so that I can store the address returned by new()
? I plan to use new()
with different types, get the allocated address and map it with the creation time.
You can use the type Pointer
from the unsafe
package, but that is, the package name implies it, unsafe. The address itself is a opaque thing and there's only little use in actually using a address value alone for a map, better use a tuple of type and address. That's what unsafe.Reflect
does provide you. The package reflect
offers you the function UnsafeAddr
and a lot more.
I suggest you read the package documentation for reflect
and unsafe
packages.
Use uintptr, an unsigned integer large enough to store the uninterpreted bits of a pointer value, as the memory map key type.
For example,
package main
import (
"fmt"
"time"
"unsafe"
)
type T struct{ a, b int }
func main() {
memmap := make(map[uintptr]int64)
pT := new(T)
memmap[uintptr(unsafe.Pointer(pT))] = time.Nanoseconds()
pT.a = 1
pT.b = 2
fmt.Printf("%d %d %p %T
", pT.a, pT.b, pT, pT)
pI := new(int)
memmap[uintptr(unsafe.Pointer(pI))] = time.Nanoseconds()
*pI = 42
fmt.Printf("%d %p %T
", *pI, pI, pI)
fmt.Printf("
%T
", memmap)
for k, v := range memmap {
fmt.Printf("%x: %d
", k, v)
}
}
Output:
1 2 0xf8400001f8 *main.T
42 0xf8400001f0 *int
map[uintptr] int64
f8400001f0: 1306837191421330000
f8400001f8: 1306837191421293000