title: Static Initialization in Go?
body: <p>I'm currently working on the Go Lang tutorial, but ran into problem with one of the exercises:</p>
  
  <p><a href="https://tour.golang.org/methods/23" rel="noreferrer">https://tour.golang.org/methods/23</a></p>
  
  <p>The exercise has me implement a ROT13 cipher. I decided to implement the cipher using a map from a byte to its rotated value but I'm not sure of the best way to initialize this map. I don't want to initialize the map using a literal, but would prefer to do it programmatically by looping through an alphabet and setting (key, value) pairs within the loop. I would also like the map to only be accessible from Rot13Reader struct/object and have all instances(?) share the same map (rather than one copy per Rot13Reader).</p>
  
  <p>Here's my current working Go program:</p>
  
  <pre><code>package main
  
  import (
      "io"
      "os"
      "strings"
  )
  
  type rot13Reader struct {
      r io.Reader
  }
  
  var rot13Map = map[byte]byte{}
  
  func (rotr *rot13Reader) Read(p []byte) (int, error) {
      n, err := rotr.r.Read(p)
      for i := 0; i &lt; n; i++ {
          if sub := rot13Map[p[i]]; sub != byte(0) {
              p[i] = sub
          }
      }
      return n, err
  }
  
  func main() {
      func() {
          var uppers = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
          var lowers = []byte("abcdefghijklmnopqrstuvwxyz")
  
          var init = func (alphabet []byte) {
              for i, char := range alphabet {
                  rot13_i := (i + 13) % 26
                  rot13Map[char] = alphabet[rot13_i]
              }
          }
  
          init(uppers)
          init(lowers)
      }()
  
      s := strings.NewReader("Lbh penpxrq gur pbqr!")
      r := rot13Reader{s}
      io.Copy(os.Stdout, &amp;r)
  }
  </code></pre>
  
  <p>Here are the problems I have with this:</p>
  
  <ul>
  <li>I don't want to have to prepare <code>rot13Map</code> in <code>main()</code></li>
  <li>I don't want <code>rot13Map</code> to be in global scope.</li>
  <li>I don't want each copy of a <code>rot13Reader</code> to have a separate <code>rot13Map</code></li>
  </ul>
  
  <p>Is there a way to achieve what I want in Go?</p>