This is a creation in Article, where the information may have evolved or changed.
Note that this type of conversion is only suitable for simple types and is completely inapplicable for types that have object descriptions.
For more detailed articles, please see @ Chen Yi Hui http://my.oschina.net/goal/blog/193698
PS: Add another usage, this time it's not chicken.
The go language is a strongly typed language. That is, go has strict type requirements, and different types cannot perform assignment operations. pointers are also objects of a definite type and are strictly type checked. The following code generates a compilation error
package mainimport ( "fmt")func main() { u := uint32(32) i := int32(1) fmt.Println(&u, &i) // 打印出地址 p := &i // p 的类型是 *int32 p = &u // &u的类型是 *uint32,于 p 的类型不同,不能赋值 p = (*int32)(&u) // 这种类型转换语法也是无效的 fmt.Println(p)}
The pointer method provided by the unsafe package can accomplish this task
package mainimport ( "fmt" "unsafe")func main() { u := uint32(32) i := int32(1) fmt.Println(&u, &i) p := &i p = (*int32)(&u) p = (*int32)(unsafe.Pointer(&u)) fmt.Println(p)}
Add: The actual use of unsafe scenarios are few, slightly more complex structure, such as struct,unsafe can not be applied, the correct method is to rely on the type assertion
PS: Discover a usage, see Code
Package MainImport("FMT" "Text/template" "unsafe")//MyTemplateDefinition andTemplate.TemplateJust shapedtypeMyTemplatestruct {NamestringParsetree *unsafe.PointerCommon *unsafe.PointerLeftdelimstringRightdelimstring}func Main () {t: =Template.New("Foo") P: = (*MyTemplate) (unsafe.Pointer(t)) P.name ="Bar"The key here is to break through the private member FMT.Println(P, t)}
Output results
&{bar <nil> <nil>} &{bar <nil> <nil>}
T.name also became bar, successfully breaking the template. Template Private Field Name