Importing local libraries into GO

Asked

Viewed 145 times

0

I’m having a hard time importing a library from do go. The library is in a folder in the same project directory and always of the import error, when not of the import error, of the error to access the function.

inserir a descrição da imagem aqui

main go.

package main

import (
    "fmt"
    "./test"
)

func main(){
    test.makeCalc(1,1)
    fmt.Println("test.makeCalc(3,6)")
}

test go.

package test

func makeCalc(x int, y int) int{
    return x+y
}
  • 1

    where is your project? within the GOROOT?

  • no, it’s in a normal folder /home/user/projecst/go/test/

  • According to the specification, the interpretation of the import depends on the compiler implementation. I recommend using import with the canonical name of the package.

1 answer

1


First create the following folder structure:

/path/to/app
  |-main.go
  |-src
     |-test
        |-test.go

Make sure that /path/to/app is included in GOPATH. Otherwise, include it:

$ # em linux
$ cd /path/to/app
$ export GOPATH=$GOPATH:/path/to/app

The code that is in test.go, to be used in main.go, needs to be exported, so use:

package test

func MakeCalc(x int, y int) int{
    return x+y
}

I hope I’ve helped!

  • According to the documentation, GOPATH is the folder where the desktop is. From what I understand, it cannot be composed of multiple paths. To set this variable in the bash use $ export GOPATH=/pasta/para/a/area/de/trabalho. reference: Setting GOPATH

  • 2

    Yes, it can be composed of multiple locations! The difference is that the first location defined will be the location where libraries will be installed by default that will be installed during the preparation phase of the project.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.