英文:
storing and retrieving byte representation of interface
问题
我有一个需要存储和检索interface{}值的字节表示的需求。为了澄清,我不是试图将底层值打包到一个切片中,无论它们的大小是多少,而是在寻找一种存储指向这些值的指针的方法。
我正在查看reflect和unsafe包来实现这一点,我看到了像UnsafeAddr
这样返回指针的方法。我可以使用存储该指针,然后在以后将其解码回我的interface{}值吗?
另一个我看到的函数是InterfaceData
,它返回一个2字节的数组表示,但有没有办法将其转换回interface值?
我的高级目标是:
// 将dataIn的指针存储在切片b中
func putPtr(b []byte, dataIn interface{}) { ... }
// 从b中返回指向的interface值
func getInter(b []byte) interface{} { ... }
英文:
I have a need to store and retrieve the byte representation of interface{} values. To clarify i'm not trying to store the underlying values packed into a slice, whatever size they may be, but looking for a way to store pointers to said values.
The reason I can't just go type MyType interface{}; var arr []MyType
is because I am packing non uniform amounts of other bytes within this array.
To implement this I am looking at the reflect and unsafe packages, and I see methods like UnsafeAddr
which return a pointer. Could I use store that pointer and then decode it back into my interface{} value later?
Another function I see is InterfaceData
which gives back a 2 byte array representation, but is there any way to turn that back into an interface value again?
My high level goal is this:
// store the pointer to dataIn in the slice b
func putPtr(b []byte, dataIn interface{}) { ... }
// return the pointed to interface value from within b
func getInter(b []byte) interface{} { ... }
答案1
得分: 5
无论你为此有什么原因,它都不能保证在一般情况下起作用。一旦你将指针隐藏在垃圾收集器(GC)的意识之外,然后通过任何可能的手段使其重生,它(指针)可能就不再有效。这是垃圾收集器工作的整个原则。
为了绕过这个失败,必须在其他地方保持指针对垃圾收集器可见,它必须保持可达性,以便垃圾收集器不会在任何(不可预测的)时刻收集它。
但是,如果一个普通且可达的指针表示可用,那么实际上就没有必要使用任何其他(比如编码在[]byte中)表示。
英文:
Whatever reason you have for this, it is guaranteed to not work in the general case. Once you hide a pointer from the garbage collector (GC) awareness and then reincarnate it by any trick possible, it (the pointer) may be not valid anymore. It's the whole principle how the GC works.
To bypass this failure, one has to keep the pointer visible to the GC elsewhere, it must remain reachable for the GC not to collect it at any (unpredictable) moment.
But if one has a normal and reachable representation of the pointer available then there really is no need for any other (like encoded in []byte) representation in the first place
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论