Skip to content

Instantly share code, notes, and snippets.

@wrfly
Created December 12, 2018 03:35
Show Gist options
  • Save wrfly/a7a1cec0cd2fcab42300d935b3f0eb9f to your computer and use it in GitHub Desktop.
Save wrfly/a7a1cec0cd2fcab42300d935b3f0eb9f to your computer and use it in GitHub Desktop.
use unsafe to convert two different types and modify them
package main
import (
"fmt"
"unsafe"
)
type A struct {
ID int
Name string
Country string
}
type B struct {
ID int
Name string
}
func main() {
aSlice := []*A{
&A{
ID: 1,
Name: "name-1",
Country: "country-1",
},
&A{
ID: 2,
Name: "name-2",
Country: "country-2",
},
}
aSlice = nil
changeID(aSlice)
for _, v := range aSlice {
fmt.Println(v)
}
}
func changeID(x []*A) {
bslice := *(*[]*B)(unsafe.Pointer(&x))
for i := range bslice {
bslice[i].ID += 10
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment