On Mon, Feb 13, 2023 at 6:48 PM Pat Farrell <pat22...@gmail.com> wrote:

> This won't compile
>
> var ExtRegex =
> regexp.MustCompile("(M|m)(p|P)(3|4))|((F|f)(L|l)(A|a)(C|c))$")
>
> with a
> ./prog.go:10:18:
> regexp.MustCompile("((M|m)(p|P)(3|4))|((F|f)(L|l)(A|a)(C|c))$") (value of
> type *regexp.Regexp) is not constant
>
That error indicates that you wrote `const ExtRegex = ....`

>
> while
> const pat = "((M|m)(p|P)(3|4))|((F|f)(L|l)(A|a)(C|c))$"
> var ExtRegex = regexp.MustCompile(pat)
>
> Works fine.
> So, why can't the regexp be a constant?
>
 Only primitive types are allowed to be constant in go
<https://go.dev/ref/spec#Constants>

> Is there some state that is kept in the regexp.Regexp store?
>
It used to, but that was removed in an earlier version (see the deprecation
notice on regexp.Copy <https://pkg.go.dev/regexp#Regexp.Copy>)

>
> And perhaps more importantly, what is the proper go style to
> have a compiled regexp?
> I could put the var statement outside all blocks, so its in effect
> a package variable. But I think having package variable is bad form.
>
For cases like this, I tend to create an unexported package variable that's
initialized with MustCompile.
package-level variables are generally bad-form, but there are cases where
you have mostly-readonly things that must be initialized at startup in
which they make sense. (constant-initialized regexps are one of these)

>
> I'm using the regexp in a loop for all the strings in all the files in a
> directory tree.
> I really don't want to compile them for ever pass thru the lines
>
> Thanks
> Pat
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/39ae6e9f-1c27-45cd-93c2-39a3b75cc6a3n%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/39ae6e9f-1c27-45cd-93c2-39a3b75cc6a3n%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CANrC0Bj8UUaNeq0pKrx_xUrDkndaS13e4LBPnp5TdAZctBsG3Q%40mail.gmail.com.

Reply via email to