Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in importing custom packages in Go Lang

Tags:

go

I have created a library by the name libfastget which is in the src with my program as

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

and the libfastget exports a 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 upon trying to build with go build

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

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

like image 230
Shenal Silva Avatar asked Aug 26 '14 09:08

Shenal Silva


People also ask

How do I import custom packages to Go?

You will first need to run the command go mod init mycode (make sure you are under ../mycode directory). Now you create package diffcode and it has some files. To import this package, you need to put this into main.go : module/package . In this case, mycode/diffcode .

Which one is the correct way to import multiple packages libraries in Golang?

Both single and multiple packages can be imported one by one using the import keyword.


2 Answers

you would need to make your function exportable with an uppercase for its name:

func Fastget(...

Used as:

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

The spec mentions: "Exported identifiers":

An identifier may be exported to permit access to it from another package. An identifier is exported if both:

  • the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
  • the identifier is declared in the package block or it is a field name or method name.

All other identifiers are not exported.

like image 138
VonC Avatar answered Oct 16 '22 15:10

VonC


to export a function into another package the function identifier must start with a capital letter.

like image 34
Sandeep kumar singh Avatar answered Oct 16 '22 17:10

Sandeep kumar singh