Error importing custom packages into Go Lang

I created a library called libfastget which is in src with my program as

 src |-libfastget | |-libfastget.go | |-MainProgram |-main.go 

and libfastget exports funtion fastget as follows

 package libfastget import ( "fmt" "io" ) func fastget(urlPtr *string, nPtr *int, outFilePtr *string) download { ..... return dl } 

When I use the library in my main program

 package main import ( "fmt" "net/http" "os" "libfastget" "path/filepath" "strings" "flag" "time" ) func uploadFunc(w http.ResponseWriter, r *http.Request) { n:=libfastget.fastget(url,4,filename) } } 

I get the following error when trying to build using go build

 # FServe ./main.go:94: cannot refer to unexported name libfastget.fastget ./main.go:94: undefined: libfastget.fastget 

It is strange that the library file libfastget.a is present in the pkg folder.

+25
go
source share
4 answers

you will need to make your function exportable with a capital letter for its name:

 func Fastget(... 

Used as:

 n:=libfastget.Fastget(url,4,filename) 

The specification states: " Exported identifiers ":

An identifier can be exported to allow access to it from another package. The identifier is exported if both:

  • the first character of the identifier name is the Unicode uppercase letter (Unicode class " Lu "); and
  • the identifier is declared in the block or this field is the name or the name of the method .

All other identifiers are not exported.

+64
source share

I recently started learning GO Lang (2 days ago). I found that you need to configure the workspace folder so that local packages are imported into other projects or main.go files. I am using VS Code Editor. Please correct me if I am wrong, but this setup works fine for me.

Inside your bash_profile OR .zshrc add the lines below, update GOPATH according to the path to your folder.

 export GOPATH=~/projects/GO_PROJECTS export PATH=$PATH:$GOPATH/bin:$PATH 

enter image description here

and this is my sayHello.go file, note, in order to be able to export the function, the name func should start with CapitalCase SayHello

 package utils import "fmt" func SayHello() { fmt.Println("Hello, Ajinkya") } 

and now I can import the utility package into the main.go file

 package main import ( "go_proj1/utils" ) func main() { utils.SayHello() } 
0
source share

I found this library very useful for importing unexported functions into Go. Please read README carefully before use. https://github.com/alangpierce/go-forceexport

0
source share

  • set current directory as GOPATH
  • or you can use local import as follows


    move your main.go to ../ directory on libfastget.go.
    I mean, the files look like this:
    CSI
    | -libfastget
    | | -libfastget.go
    |
    | -main.go

import "./libfastget"
-one
source share

All Articles