如何使用go复制公共变量?

How to copy a public variable use go?

For example, a public variadble named PublicVar

a := []string{"A", "B"}
b := a
fmt.Printf("%v
", a)
fmt.Printf("%v
", b)

b[0] = "C"
fmt.Printf("%v
", a)
fmt.Printf("%v
", b)
// a has been changed.

The PublicVar's name will be changed, but this is not what I want.

I just want to copy the value of PublicVar.

This happen because probably PublicVar is a pointer to an instance. So temp is also pointing to the same instance. You can get a value type by following.

temp := *PublicVar
temp.name = "bob"

See an example at Playground

Edit: Since the question is edited to show the variable of concern is a slice, khrm's answer is more relevant.

Go copy by value. But in case of maps and slices, there is an exceptions in that only their reference is copied as they are implemented as reference type.

In case of slice, you can do this using builtin copy:

b := make([]string, len(a))
copy(b,a)

In case of maps:

for k, v := range a {
    b[k] = v
}