---
# System prepended metadata

title: luck is a choice
tags: [note]

---

###### tags: `note`

luck is a choice
===

```go=
package main

import (
	"fmt"
	"reflect"
)

func main() {
	cloneSlice()
	cloneMap()
}

func cloneSlice() {
	content := []string{"foo", "bar"}
	in := reflect.ValueOf(content)
	size := len(content)

	out := reflect.MakeSlice(in.Type(), size, size)
	for i, elem := range content {
		out.Index(i).SetString(elem)
	}

	for i, v := range out.Interface().([]string) {
		fmt.Printf("%d: %v\n", i, v)
	}
}

func cloneMap() {
	content := map[string]string{
		"foo": "FOO",
		"bar": "BAR",
	}
	in := reflect.ValueOf(content)

	out := reflect.MakeMap(in.Type())
	for k, v := range content {
		out.MapIndex(reflect.ValueOf(k)).SetString(v) // unlucky :(
		// if you want assign value into the map, you should use Value.SetMapIndex(k, v)
		// e.g:
		//    out.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(v))
		//
		// good luck!
	}

	for k, v := range out.Interface().(map[string]string) {
		fmt.Printf("%v: %v\n", k, v)
	}
}
```
🎬 https://go.dev/play/p/3s23CVqX-lh


⠿ 要填入 map 的值可使用下面的方式：
```go=
package main

import (
	"fmt"
	"reflect"
)

func main() {
	content := map[string]string{
		"foo": "FOO",
		"bar": "BAR",
	}
	var outType reflect.Type = reflect.TypeOf(map[string]***string{})

	out := reflect.MakeMap(outType)
	for k, v := range content {
		var rv reflect.Value
		{
			/* NOTE: The reflection statements same as
			 * 
			 *    var elem **string
			 *    **elem = v
			 *    out[k] = elem
			 */
			var rvpcount int = 0
			var rvt reflect.Type = out.Type().Elem()
			for {
				if rvt.Kind() != reflect.Ptr {
					break
				}
				rvpcount++
				rvt = rvt.Elem()
			}
			rv = reflect.New(rvt).Elem()
			rv.SetString(v)
			for i := 0; i < rvpcount; i++ {
				if rv.CanAddr() {
					rv = rv.Addr()
				} else {
					parent := reflect.New(rv.Type())
					parent.Elem().Set(rv)
					rv = parent
				}
			}
		}
		out.SetMapIndex(reflect.ValueOf(k), rv)
	}

	for k, v := range out.Interface().(map[string]***string) {
		fmt.Printf("%v: %v\n", k, ***v)
	}
}
```
🎬 https://go.dev/play/p/M4XAuL8zAFl