Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Global variables

Tags:

go

I can easily make an object global by defining it outside of any function, but this does not work for certain structs that must be created.

What I'm trying to do is a much more complicated version of this:

package main
import "regexp"

func doSomething(test []byte) []byte {
   test = reg.ReplaceAll(test,nil)
   return test
}

reg, _ := regexp.Compile(`[^a-z\s]`) // this is the issue

func main() {
   thing := doSomething("somebytes")
}

Obviously the above is not allowed, but that's what I'd like to do.

There does not appear to be any way to make that reg object accessible from within the doSomething function without passing it, which I want to avoid because I'm going to be doing this several billion times.

If I put it in main() then it's no longer global. I've even tried this:

var reg regexp.Regexp
func main() {
   reg, _ = regexp.Compile(`[^a-z\s]`)
   thing := doSomething("somebytes")
}

...but that doesn't work either, it gives me an error.

Any ideas?

Update: My issue is not actually with regexp. That was an example.

like image 338
Alasdair Avatar asked Aug 02 '14 15:08

Alasdair


Video Answer


2 Answers

It's allowed just fine, you can use:

var reg = regexp.MustCompile(`[^a-z\s]`) //or even
var reg, _ = regexp.Compile(`[^a-z\s]`) // MustCompile is the better choice though.

Also keep in mind that regexp.Compile / regexp.MustCompile returns a pointer, and that's why your 2nd attempt didn't work, you were assigning *regexp.Regexp to regexp.Regexp.

Full example:

func doSomething(test []byte) []byte {
    test = reg.ReplaceAll(test, nil)
    return test
}

var (
    reg, _ = regexp.Compile(`[^a-z\s]`)
    reg2   *regexp.Regexp
)

func init() { //different way of initializing global valuables
    reg2 = regexp.MustCompile(`[^a-z\s]`)
}

func main() {
    thing := doSomething([]byte("somebytes"))
    fmt.Println(thing)
}
like image 90
OneOfOne Avatar answered Sep 29 '22 03:09

OneOfOne


The short declaration syntax

reg, _ := regexp.Compile(`[^a-z\s]`)

is not allowed for global scope. Use var explicitly instead.

var reg, _ = regex.Compile(`[^a-z\s]`)
like image 31
fuz Avatar answered Sep 29 '22 02:09

fuz