How to pass Regex in golang function - go

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?

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

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

Related

How to fail/exit execution of a golang program when environment variable not found?

I need to read an environment variable SubscriptionID to golang-variable subId. My program works well when it can read env variable SubscriptionID. Program runs to completion even it can't find env var & produces unexpected result.
How to make it fail(exit execution) if it can't find an environment variable?
package main
import (
"fmt"
"os"
)
func main(){
subId := os.Getenv("SubscriptionID")
fmt.Printf("SubscriptionID: %v\n", subId)
}
Package os
import "os"
func LookupEnv
func LookupEnv(key string) (string, bool)
LookupEnv retrieves the value of the environment variable named by the
key. If the variable is present in the environment the value (which
may be empty) is returned and the boolean is true. Otherwise the
returned value will be empty and the boolean will be false.
For example,
package main
import (
"fmt"
"os"
)
func main() {
subId, present := os.LookupEnv("SubscriptionID")
if !present {
fmt.Printf("SubscriptionID: not present\n")
return
}
fmt.Printf("SubscriptionID: %v\n", subId)
}
Playground: https://play.golang.org/p/t-HAS0zC3M7
Output:
SubscriptionID: not present

Golang local import

I am attempting to do a local import but it fails.
My environment is:
echo $GOPATH
/home/peter/go
echo $GOROOT
/usr/local/go
The entry point is:
/home/peter/go/src/projects/pkgs1/main.go
The imported file is:
/home/peter/go/src/projects/pkgs2/stuff.go
main.go
package main
import (
"fmt"
"projects/pkgs2" // <- this does not resolve
)
func main(){
fmt.Println("123")
pkgs2.X()
}
stuff.go
package pkgs2
import "fmt"
func X(){
fmt.Println("X")
}
Any pointers on what I do wrong?
Your import path is correct and should resolve successfully, but as written, your program won't compile because the import isn't being used and there is no local function named x.
As mentioned by mkopriva your x function in pkgs2 isn't exported and you have not qualified it when trying to use it in your main package.
To export a function, it needs to start with a capital letter.
To use the function in another package, you need to prefix the package name to the function name.
main.go
package main
import (
"fmt"
"projects/pkgs2"
)
func main(){
fmt.Println("123")
pkgs2.X()
}
stuff.go
package pkgs2
import "fmt"
func X(){
fmt.Println("X")
}

Why function in my package is not working

I have put a small code file in $GOPATH which is ~/go/src. Here I have made a folder mysrc and there I have kept a file mytest.go, which is as follows:
package mytest
import ("fmt")
func myfn(){
fmt.Println("My own fn")
}
I try to import above code with following file:
package main
import ("mysrc")
main(){
myfn()
}
When I try to run above file, I get error:
# command-line-arguments
./useMyfn.go:3:1: syntax error: non-declaration statement outside function body
Where is the problem and how can it be solved? Thanks for your help.
Edit: I corrected the main fn to func main() but now the errors are:
# command-line-arguments
./useMyfn.go:2:9: imported and not used: "mysrc" as mytest
./useMyfn.go:4:2: undefined: myfn
You need to do few things
I suggest to use a package name that the name is same with the folder name.
The myfn() function need to be exported. How to do it: simply set the first character of the function name to uppercase.
package mysrc // <-- 1
import (
"fmt"
)
func Myfn() { // <-- 2
fmt.Println("My own fn")
}
The func keyword is required before main() statement.
To access a function from other package, you need to write down the package name before the function name. In this context it'll be mysrc.Myfn().
package main
import (
"mysrc"
)
func main() { // <-- 3
mysrc.Myfn() // <-- 4
}

Why TrimLeft doesn't work as expected?

I've expected tag to be "account" but it is "ccount". Why is "a" removed?
package main
import "fmt"
import "strings"
func main() {
s := "refs/tags/account"
tag := strings.TrimLeft(s, "refs/tags")
fmt.Println(tag)
}
Run
Use TrimPrefix instead of TrimLeft
package main
import "fmt"
import "strings"
func main() {
s := "refs/tags/account"
tag := strings.TrimPrefix(s, "refs/tags/")
fmt.Println(tag)
}
Please notice that following TrimLeft calls will result the same "fghijk
" string:
package main
import (
"fmt"
"strings"
)
func main() {
s := "/abcde/fghijk"
tag := strings.TrimLeft(s, "/abcde")
fmt.Println(tag)
tag = strings.TrimLeft(s, "/edcba")
fmt.Println(tag)
}
So TrimLeft is not the method which fits your needs. I guess it's impossible to use it in the example you've given to get the result you expect.
It is working as documented:
TrimLeft returns a slice of the string s with all leading Unicode
code points contained in cutset removed
Because there's an 'a' in the first argument (the cutset) the leading 'a' in account is removed

Cant I get rid of fmt prefix when calling Println in Golang

I tried http://tour.golang.org/#1
package main
import "fmt"
func main() {
Println("Hello World")
}
This generates error :
prog.go:3: imported and not used: "fmt"
prog.go:6: undefined: Println
[process exited with non-zero status]
Program exited
Does it mean I am obliged to prefix Println with "fmt" package name ? In other languages it isn't mandatory.
You will have to prefix a function if it is not in the current package.
What you can do however is create an alias for this package:
import f "fmt"
func main() {
f.Println("Hello World")
}
Or "rename" the function:
import "fmt"
var Println = fmt.Println
func main() {
Println("Hello World")
}
Or use . as alias (it may be what you would like most):
import . "fmt"
func main() {
Println("Hello World")
}
Note that in that case, the alias is not blank. From the specifications of Go:
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 .
And another example from the same specifications:
import "lib/math" math.Sin
import m "lib/math" m.Sin
import . "lib/math" Sin

Resources