title: Convert **T to *unsafe.Pointer in Go
body: <p>How do I convert a variable of type <code>**T</code> to <code>*unsafe.Pointer</code>?</p>
  
  <p>The example below will give the compilation error:  </p>
  
  <blockquote>
    <p>cannot convert &amp;ptr (type **s) to type *unsafe.Pointer</p>
  </blockquote>
  
  <pre><code>package main
  
  import (
      "sync/atomic"
      "unsafe"
  )
  
  type s struct {
      value int
  }
  
  func main(){
      var ptr *s
      a := &amp;s{42}
  
      old := ptr
      atomic.CompareAndSwapPointer(
          (*unsafe.Pointer)(&amp;ptr), // &amp;unsafe.Pointer(ptr)
          unsafe.Pointer(old),
          unsafe.Pointer(a))
  }
  </code></pre>
  
  <p>If I switch <code>(*unsafe.Pointer)(&amp;ptr)</code> to <code>&amp;unsafe.Pointer(ptr)</code>, I will get this compilation error:</p>
  
  <blockquote>
    <p>cannot take the address of unsafe.Pointer(ptr)</p>
  </blockquote>
  
  <p>Ps. I choose to make an example with <code>sync/atomic</code> because that is one situation where you actually have to do such a conversion.</p>
  
  <p><strong>Edit</strong></p>
  
  <p>One incorrect solution would be to use a temporary variable:</p>
  
  <pre><code>up := unsafe.Pointer(ptr)
  atomic.CompareAndSwapPointer(&amp;up, ...
  </code></pre>
  
  <p>While it compiles, the CAS will only swap what is stored in <code>up</code> and not in <code>ptr</code>. This is not the desired result, as zeebo@#go-nuts pointed out.</p>