3

I have a data structure that only accepts strings and I want to store pointers to another data structure.

Enssentially I can save the pointers as string as such:

ptr := fmt.Sprint(&data) // ptr is now something like : 0xc82000a308

then later on I want to get the stuff store at the ptr, is there a way to cast this ptr to a pointer type?

1
  • 1
    Never ever do that. It is possible but your code will break because the GC won't see your stringified pointers and might collect stuff. Commented Jun 23, 2016 at 21:20

1 Answer 1

5

Sure, you can do that using the unsafe package:

https://play.golang.org/p/Wd7hWn9Zsu

package main

import (
    "fmt"
    "strconv"
    "unsafe"
)

func main() {
    //Given:
    data := "Hello"
    ptrString := fmt.Sprintf("%d", &data)

    //Convert it to a uint64
    ptrInt, _ := strconv.ParseUint(ptrString, 10, 64)

    //They should match
    fmt.Printf("Address as String: %s as Int: %d\n", ptrString, ptrInt)

    //Convert the integer to a uintptr type
    ptrVal := uintptr(ptrInt)

    //Convert the uintptr to a Pointer type
    ptr := unsafe.Pointer(ptrVal)

    //Get the string pointer by address
    stringPtr := (*string)(ptr)

    //Get the value at that pointer
    newData := *stringPtr

    //Got it:
    fmt.Println(newData)

    //Test
    if(stringPtr == &data && data == newData) {
        fmt.Println("successful round trip!")
    } else {
        fmt.Println("uhoh! Something went wrong...")
    }
}

However, keep in mind the various warnings on the unsafe package. For example:

"A uintptr is an integer, not a reference. Converting a Pointer to a uintptr creates an integer value with no pointer semantics. Even if a uintptr holds the address of some object, the garbage collector will not update that uintptr's value if the object moves, nor will that uintptr keep the object from being reclaimed." - https://golang.org/pkg/unsafe/#Pointer

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.