Created
December 12, 2018 03:35
-
-
Save wrfly/a7a1cec0cd2fcab42300d935b3f0eb9f to your computer and use it in GitHub Desktop.
use unsafe to convert two different types and modify them
This file contains hidden or 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" | |
) | |
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