Skip to content

Instantly share code, notes, and snippets.

@snyh
Created June 30, 2016 00:47
Show Gist options
  • Save snyh/8971bdf0e3768bc723129d18bf3b504c to your computer and use it in GitHub Desktop.
Save snyh/8971bdf0e3768bc723129d18bf3b504c to your computer and use it in GitHub Desktop.
Implement simple containerOf in Golang
package main
import (
"fmt"
"unsafe"
)
// the dummy struct
type B struct {
dummy int
}
// the dummy container
type A struct {
foo string
B
D string
}
func (this *B) ContainerA() A {
return *(*A)((unsafe.Pointer)((uintptr(unsafe.Pointer(this)) - unsafe.Offsetof(A{}.B))))
}
func main() {
a := A{"foo", B{}, "hehe"}
b := &(a.B) // the b must be a pointer
fmt.Println(b.ContainerA())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment