Go module and importing local package

(Garag) #1

Hi everyone

I encounter issue regarding the use of go module.

My project example is structure as follow:

--------- bar.go
--------- bar_test.go
--------- testmod/
--------------- main.go
--------- foo.go
--------- foo_test.go

My go.mod is defined as follow

module example.org/maadam/testmod

require (
	github.com/davecgh/go-spew v1.1.1 // indirect
	github.com/pmezard/go-difflib v1.0.0 // indirect
	github.com/stretchr/testify v1.2.2


package foo

import (

func ConvertInt2String(num int) string {
	return strconv.Itoa(num)


package bar

import (

func ConvertString2Int(num string) (int, error) {
	return strconv.Atoi(num)


package main

import (


func main() {
	iFoo := 2
	strFoo := ConvertInt2String(iFoo)
	fmt.Printf("foo.ConvertInt2String %d : %s", iFoo, strFoo)

	strBar := "28"
	iBar, _ := ConvertString2Int(strBar)
	fmt.Printf("bar.ConvertString2Int %s : %d", strBar, iBar)

I thought that as my module name was example.org/maadam/testmod, I could import my packages foo or bar by using example.org/maadam/testmod/foo or /bar.
But when I am trying to build cmd/testmod/main.go, I have the following errors:

> go build cmd/testmod/main.go 
> # command-line-arguments
> cmd/testmod/main.go:6:2: imported and not used: "example.org/maadam/testmod/foo"
> cmd/testmod/main.go:7:2: imported and not used: "example.org/maadam/testmod/bar"
> cmd/testmod/main.go:12:12: undefined: ConvertInt2String
> cmd/testmod/main.go:16:13: undefined: ConvertString2Int

Can you help me understand what I am doing wrong with go module for importing my package? Or is it just the project structure that is not compatible with?


(Garag) #2

Ok so I found my mistake… I have to call the function with the name of package I imported: foo.ConvertInt2String() and bar.ConvertString2Int()…