Go and copies

omarkhatib

Omar

Posted on July 16, 2021

Go and copies

Copying concept was always weird for me , when I learned GO it was like why? Why! Why GO favorite option is to work on a copy?!
Today I make discovery that I will like to share.

I was reading a book "composing software" and I see an example about Shared State.
"Shared-state concurrency means that concurrent computations communicate through reading and updating a shared location in memory."-source

I know the title said GO but the examples that let me understand the importance of copying in GO was an example in the book which is JavaScript , so the examples are in JavaScript.

Let's take a look at this example taken from the book.

// Shared state
const x = {
    val: 2
};

// Mutates shared state
const x1 = () => x.val += 1;

// Mutates shared state
const x2 = () => x.val *= 2;

x1();
x2();

console.log(x.val); // 6

// This example is exactly equivalent to the above, except...
const y = {
    val: 2
};

const y1 = () => y.val += 1;

const y2 = () => y.val *= 2;

// ...the order of the function calls is reversed...
y2();
y1();

// ... which changes the resulting value:
console.log(y.val); // 5
Enter fullscreen mode Exit fullscreen mode

this code seems logical , but let's say we have 2 threads (or routines) accessing the same object x in same time.
both of them are modifying the same object , so the output depends on race condition.

so to avoid this we use (yes you guess it) a copy!

const x = {
    val: 2
};

const inc = x => ({...x, val: x.val + 1});
const double = x => ({...x, val: x.val * 2});

console.log(inc(double(x)).val); // 5

const y = {
    val: 2
};

/*
Because the functions don't mutate, you can call
these functions as many times as you want, in any order,
without changing the result of other function calls.
*/

// These calls do nothing:
inc(y);
double(y);

console.log(inc(double(y)).val); // 5
Enter fullscreen mode Exit fullscreen mode

the three dots ... are spread operator basically it will copy the propriety of the object and the function will return a new copy with modified value. Once I read this code I directly remembered GO , the idea in GO that everything is a copy was weird for me. And as we know go main feature is concurrency so everything as a copy seemed a very good and safe choice by go designers.
so the advantage of working on a copy is safety , isolation , multi threading , but it also have disadvantage like deficiency.

That's why we like in GO to avoid as much as we can using pass as pointer.

that was my discovery today that I liked to share with community , please if you have more information that can help us , share it with us!

💖 💪 🙅 🚩
omarkhatib
Omar

Posted on July 16, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Go and copies
go Go and copies

July 16, 2021