Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined: function (declared in another package)

Tags:

go

my project organisation looks like this :

  • GOPATH
    • src
      • cvs/user/project
        • main.go
        • utils
          • utils.go

main.go looks like this :

package main

import (
  "fmt"
  "cvs/user/project/utils"
)

func main() {
   ...
   utilsDoSomething()
   ...
}

and utils.go :

package utils

import (
  "fmt"
)   

func utilsDoSomething() {
    ...
}

The compiler tells me that :

main.go imported and not used: "cvs/user/project/utils"

main.go undefined: utilsDoSomething

I don't know what I'm doing wrong. Any idea would be helpful, thank you in advance !

like image 378
Xys Avatar asked Dec 18 '22 17:12

Xys


2 Answers

You forgot the package prefix in main.go and your function is not exported, meaning it is not accessible from other packages. To export an identifier, use a capital letter at the beginning of the name:

utils.UtilsDoSomething()

Once you have the utils prefix you can also drop the Utils in the name:

utils.DoSomething()

If you want to import everything from the utils package into the namespace of your main application do:

import . "cvs/user/project/utils"

After that you can use DoSomething directly.

like image 132
nemo Avatar answered Dec 21 '22 06:12

nemo


When you are referencing a function from a package you need to reference it using the package name.Function name (with capital case).

In your case use it as:

utils.UtilsDoSomething().

like image 26
Endre Simo Avatar answered Dec 21 '22 05:12

Endre Simo