Skip to content

Instantly share code, notes, and snippets.

@knzm
Created September 22, 2017 10:54
Show Gist options
  • Save knzm/04d393e5b5f4f09700a33e36683117c2 to your computer and use it in GitHub Desktop.
Save knzm/04d393e5b5f4f09700a33e36683117c2 to your computer and use it in GitHub Desktop.
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