How to import local packages in go?

1

I am new to golang and I need to understand how GO implements the packages in general. I want to implement a local package to separate my code and keep it organized.

I have the following example:

nums.go

package nums

func Even(i int) bool {
  return i % 2 == 0
}

func Odd(i int) bool {
  return i % 2 == 1
}

main.go

package main

import (
  "./nums"
  "fmt"
)

func main() {
  a := 5
  b := 6

  fmt.Printf("%d is even %v?\n", a, nums.Even(a))
  fmt.Printf("%d is odd %v?\n", b, nums.Odd(b))
}

Trying to run the go run main.go command throws me the following error:

  

main.go: 4: 5: open / home / ubuntu / workspace / nums: no such file or directory

Why is this? What am I doing wrong?

    
asked by Juan Pablo 01.09.2016 в 17:06
source

2 answers

0

The problem is that your package " nums " does not exist. The folder structure should be the following:

project/
 nums/
    nums.go
    another-package.go
 main.go

To better understand golang, I recommend reading the official tutorial: How to Write Go Code .

    
answered by 01.09.2016 / 19:18
source
0

If you use the order of your folders correctly as specified in the go tutorial on how to write go code you can import them from the following way:

"github.com/tu_usuario_de_github/nombre_del_paquete"

The packages that you develop can be integrated with github, that's why you need the folder of your github username, you can also download packages developed by other people.

    
answered by 08.11.2016 в 22:19