-
Notifications
You must be signed in to change notification settings - Fork 18k
cmd/go2go: invalid unsafe.Sizeof operation on parametric type #43208
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
It's a complex issue because |
Because I don't think this is an issue with cmd/go2go, I'm going to close this issue. This is something to bring up during or after the discussion of the generics proposal itself. |
Thanks @ianlancetaylor for the explanation. FYI, my use case for this was that I was trying to write a generic function to obtain the exact index of a pointer to an element in a slice: // IndexPointer returns the index of the element in s that is exactly identical to p,
// or -1 if p is not present in s.
func IndexPointer[T any](s []T, p *T) int {
if len(s) == 0 || p == nil {
return -1
}
if &s[0] == p {
return 0 // handles the special case where unsafe.Sizeof(T) is zero
}
var t T
offset := uintptr(unsafe.Pointer(p)) - uintptr(unsafe.Pointer(&s[0]))
index := offset / unsafe.Sizeof(t)
if index < uintptr(len(s)) && &s[index] == p {
return int(index)
}
return -1
} Without the use of unsafe, I don't believe there is a way to do the above in O(1), the best in O(n): func IndexPointer[T any](s []T, p *T) int {
for i := range s {
if &s[i] == p {
return i
}
}
return -1
} There have been several times where I needed an operation like this, and it would be nice if a standard library function in Go 2 provided it. |
How about |
uintptr(unsafe.Pointer(&s[1])) - uintptr(unsafe.Pointer(&s[0]))
Have to handle lengths 0 and 1 specially, of course.
…On Thu, Dec 17, 2020 at 9:40 PM Ian Lance Taylor ***@***.***> wrote:
How about reflect.TypeOf(t).Size()?
—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
<#43208 (comment)>, or
unsubscribe
<https://github.com/notifications/unsubscribe-auth/ABUSAIGP3SIPT5L3GLBQUTTSVLTLBANCNFSM4U5QZZXA>
.
|
Possibly a duplicate of #40301 |
Yes, this is essentially #40301; thanks @AndrewWPhillips . |
Consider this snippet:
Compiling this currently errors with:
I may be a bit behind on the latest with the generics proposal, but it seems to me that
unsafe.Sizeof
should work for parametric types.\cc @griesemer
The text was updated successfully, but these errors were encountered: