Golang Coercion type conversion: unsafe. Pointer

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.