Can let an any, its typ type metadata and data value do not match?

49 views
Skip to first unread message

qiu laidongfeng2

unread,
Oct 3, 2024, 9:25:55 AM10/3/24
to golang-nuts

In #21031, this can be optimized to reduce the Pointer,usage atomic-operate for any type, as shown in https://go-review.googlesource.com/c/go/+/617695 .


But we need support for setting atomic values to nil, and we also need a way to represent deleted values.

The current practice is to make a spin lock using the typ field of any.


I want to ask if we can do better this way:

typ remains unchanged after the first setting,Cases such as being deleted are represented by a special internal package pointer, which is set to data field.


An example to illustrate this approach:


```go

package main


import (

"sync/atomic"

"unsafe"

)


var delete byte


func main() {

var v atomic.Value

var i int = 1

v.Store(i)

// Make a any , it is typ=int meta data,data=&byte

nv := new_delete(getIntType())

// Indicates deleted

v.Store(nv)

}


type iface struct {

typ, data unsafe.Pointer

}


func new_delete(typ unsafe.Pointer) any {

ret := iface{

typ: typ,

data: unsafe.Pointer(&delete),

}

return *(*any)(unsafe.Pointer(&ret))

}


func getIntType() unsafe.Pointer {

var i int

var a any = i

var as *iface = (*iface)(unsafe.Pointer(&a))

return as.typ

}

```

Reply all
Reply to author
Forward
0 new messages