dtv7174 2014-08-02 15:40
浏览 12
已采纳

转至:全局变量

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.

  • 写回答

2条回答 默认 最新

  • dpdhnd3577 2014-08-02 15:44
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度