Static Initialization in Go? -


i'm working on go lang tutorial, ran problem 1 of exercises:

https://tour.golang.org/methods/23

the exercise has me implement rot13 cipher. decided implement cipher using map byte rotated value i'm not sure of best way initialize map. don't want initialize map using literal, prefer programmatically looping through alphabet , setting (key, value) pairs within loop. map accessible rot13reader struct/object , have instances(?) share same map (rather 1 copy per rot13reader).

here's current working go program:

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)     := 0; < 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) {             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, &r) } 

here problems have this:

  • i don't want have prepare rot13map in main()
  • i don't want rot13map in global scope.
  • i don't want each copy of rot13reader have separate rot13map

is there way achieve want in go?

in order this, make rot13 package. can programmatically create map in init() function , provide package level global rot13 decoders. init function runs when package imported.

because rot13reader type in package, 1 able access map.

warning: code untested.

package rot13  import (     "io" )  var rot13map = map[byte]byte{}  func init() {     var uppers = []byte("abcdefghijklmnopqrstuvwxyz")     var lowers = []byte("abcdefghijklmnopqrstuvwxyz")      var init = func(alphabet []byte) {         i, char := range alphabet {             rot13_i := (i + 13) % 26             rot13map[char] = alphabet[rot13_i]         }     }      init(uppers)     init(lowers) }  type reader struct {     r io.reader }  func (rotr reader) read(p []byte) (int, error) {     n, err := rotr.r.read(p)     := 0; < n; i++ {         if sub := rot13map[p[i]]; sub != byte(0) {             p[i] = sub         }     }     return n, err } 

obviously, can't make package in go tour. stuck rot13map being accessible main. need run go locally separation want.


Comments

Popular posts from this blog

c++ - Function signature as a function template parameter -

algorithm - What are some ways to combine a number of (potentially incompatible) sorted sub-sets of a total set into a (partial) ordering of the total set? -

How to call a javascript function after the page loads with a chrome extension? -