Modify dereferenced struct pointer changes most struct values, but not slices
<p>I'm trying to create a shallow copy of a struct Board (a chessboard). Before saving a move to the board, I need to check if that move puts the mover in check.</p>

<p>To do so, within the Move method (method of a pointer), I <strong>dereference</strong> the pointer, update and check this <strong><em>possible</em></strong> board for Check. When I change the value of a single value of the Board type (such as <code>possible.headers = "Possible Varient"</code>) the original <code>b</code> Board is not changed. </p>

<p>But here when I call a method updateBoard() it updates both boards. I still receive the error (cannot move into check), but the main thread thinks <code>b.board</code> (the board position) has been changed.</p>

<pre><code>func (b *Board) Move(orig, dest int) error {
    // validation
    ...
    // Update 
    possible := *b // A 'shallow copy'?
    possible.updateBoard(orig, dest, val, isEmpassant, isCastle)

    king := possible.findKingPositionOfThePlayerWhoMoved()
    isCheck := possible.isInCheck(king) // bool takes the king to check for

    if isCheck {
        return errors.New("Cannot move into Check")
    }
    b.updateBoard(orig, dest, val, empassant, isCastle)
    return nil
</code></pre>

<p>Strangely, not all the the values updated by <code>updateBoard()</code> change. So the <code>b.toMove</code> value doesn't change, but the <code>b.board</code> value does (the position of the pieces). This means if I pass <code>possible := b</code> instead, the game will only ever be white's move (toMove is alternated in the updateBoard() method). With <code>possible := *b</code>, turn alternation works until one moves into check. Then the move is applied to <code>b.board</code>, but the error is thrown back and it remains the checked-players turn (meaning <code>possible.updateBoard()</code> didn't update b.toMove.</p>

<p><strong>Edit</strong></p>

<p>As abhink pointed out, in <a href="https://blog.golang.org/go-slices-usage-and-internals" rel="nofollow">Go Slices usage and internals</a>,</p>

<blockquote>
  <p>Slicing does not copy the slice's data. It creates a new slice value that points to the original array. </p>
</blockquote>

<p><code>b.board</code>, a <code>[]byte</code>, always points to its original value (even when the struct which holds it is <strong>dereferenced</strong>. abhink's answer uses the Go <code>func copy(dst, src []Type) int</code>, <a href="https://golang.org/pkg/builtin/#copy" rel="nofollow">https://golang.org/pkg/builtin/#copy</a> , a shortcut for copying the values of the pointers.</p>