5

I want to pass a compiled regex to golang function, e.g.

package main

import "fmt"
import "regexp"

func foo(r *Regexp) {
    fmt.Println(r)    
}

func main() {

    r, _ := regexp.Compile("p([a-z]+)ch")
    foo(r)
}

But it is showing "undefined: Regexp"

Any hints?

1
  • 8
    Use the qualified name: regexp.Regexp Commented May 1, 2014 at 10:07

2 Answers 2

12

Use a qualified identifier. For example,

package main

import "fmt"
import "regexp"

func foo(r *regexp.Regexp) {
    fmt.Println(r)
}

func main() {

    r, _ := regexp.Compile("p([a-z]+)ch")
    foo(r)
}

Output:

p([a-z]+)ch

Qualified identifiers

A qualified identifier is an identifier qualified with a package name prefix. Both the package name and the identifier must not be blank.

QualifiedIdent = PackageName "." identifier .

A qualified identifier accesses an identifier in a different package, which must be imported. The identifier must be exported and declared in the package block of that package.

math.Sin  // denotes the Sin function in package math
Sign up to request clarification or add additional context in comments.

Comments

0

You can also use a dot import:

package main

import (
   "fmt"
   . "regexp"
)

func foo(r *Regexp) {
   fmt.Println(r)    
}

func main() {
   r := MustCompile("p([a-z]+)ch")
   foo(r)
}

However, typically it will be better to use use the fully qualified name.

https://golang.org/ref/spec#Import_declarations

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.