Created
June 30, 2016 00:47
-
-
Save snyh/8971bdf0e3768bc723129d18bf3b504c to your computer and use it in GitHub Desktop.
Implement simple containerOf in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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