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.
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)
}
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]`)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With