golang unsafe 指针类型 强制转换

package main

import (
	"fmt"
	"unsafe"
)

type Type1 struct {
	S1 string
}

type Type12 struct {
	S1 string
	S2 string
}

func main() {
	fmt.Println("running...")
	s12 := Type12{"123", "456"}
	fmt.Println("s12=", s12)
	s1 := (*Type1)(unsafe.Pointer(&s12))
	fmt.Println("s1=", s1)

	s := (*Type12)(unsafe.Pointer(s1))
	fmt.Println("s=", s)
	s.S2 = "abc"
	fmt.Println("s=", s)
}
make分配的虽然不是指针,但是map传递的类似引用。
struct传递的不是指针,也不是引用。
package main

import (
	"fmt"
	"reflect"
)

func main() {
	fmt.Println("running 222")

	m1 := map[string]string{"m": "m111"}
	m2 := make(map[string]string, 5)
	m2["m"] = "m222"
	m := m1
	m["x"] = "xxxx"

	s1 := make([]string, 50, 200)
	s1[0] = "s000"
	s1[49] = "s222"

	s1 = s1[0 : cap(s1)-1]
	fmt.Println(cap(s1), len(s1))

	s1[100] = "s1000"

	s2 := new([]string)
	*s2 = make([]string, 5)
	(*s2)[1] = "s1111"

	fmt.Println(reflect.TypeOf(m1), m1)
	fmt.Println(reflect.TypeOf(m2), m2)
	fmt.Println(reflect.TypeOf(m), m)

	fmt.Println(reflect.TypeOf(s1), s1)
	fmt.Println(reflect.TypeOf(s2), s2)
}
package main

import (
	"fmt"
)

type T struct {
	S string
	A []string
	M map[int]string
}

func main() {
	fmt.Println("running...")
	t1 := T{"t1", []string{"a1", "a2"}, map[int]string{1: "m1", 2: "m2"}}
	t2 := t1
	fmt.Println("t1", t1)
	fmt.Println("t2", t2)
	fmt.Println()

	t2.S = t2.S + "+"
	t2.A[0] = t2.A[0] + "+"
	t2.M[1] = t2.M[1] + "+"

	fmt.Println("t1+", t1)
	fmt.Println("t2+", t2)

	fmt.Scanln()
	fmt.Println("end")
}


发表于:2016-11-12 12:13:16

原文链接(转载请保留): http://www.multisilicon.com/blog/a36282371.html

友情链接: MICROIC
首页