Created
September 22, 2017 10:54
-
-
Save knzm/04d393e5b5f4f09700a33e36683117c2 to your computer and use it in GitHub Desktop.
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 URLString string | |
type URLStrings []URLString | |
type Strings []string | |
func unsafeCastToStringSlice(x interface{}) []string { | |
return *(*([]string))(unsafe.Pointer(&x)) | |
} | |
func (urls URLStrings) AsStrings() []string { | |
return unsafeCastToStringSlice(urls) | |
} | |
func (ss Strings) AsURLStrings() []URLString { | |
return *(*([]URLString))(unsafe.Pointer(&ss)) | |
} | |
// Patern A. Strings to URLStrings | |
func main1() { | |
ss := Strings{"a", "b", "c"} | |
urls := ss.AsURLStrings() | |
fmt.Println(urls) | |
// Output: | |
// [a b c] | |
} | |
// Pattern B. URLStrings to Strings | |
func main2() { | |
urls := URLStrings{"a", "b", "c"} | |
ss := urls.AsStrings() | |
fmt.Println(ss) | |
// panic: runtime error: invalid memory address or nil pointer dereference | |
} | |
func main() { | |
main1() | |
main2() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment