3

Here is an example of my code:

package main

import (
  "./bio"
)

func main() {
   bio.PeptideEncoding(genome, codonTable)
}

Is it possible to use functions from my paxkage (bio) without specifying package name:

func main() {
   PeptideEncoding(genome, codonTable)
}

?

ceth
  • 44,198
  • 62
  • 180
  • 289

1 Answers1

8

You could use as an import declaration like:

. "./bio"

If an explicit period (.) appears instead of a name, all the package's exported identifiers declared in that package's package block will be declared in the importing source file's file block and must be accessed without a qualifier.

That is what a testing framework like govey does:

package package_name

import (
    "testing"
    . "github.com/smartystreets/goconvey/convey"
)

func TestIntegerStuff(t *testing.T) {
    Convey("Given some integer with a starting value", t, func() {
        x := 1

        Convey("When the integer is incremented", func() {
            x++

            Convey("The value should be greater by one", func() {
                So(x, ShouldEqual, 2)
            })
        })
    })
}

You don't need to use convey.So(), or convey.Convey() because of the import starting with a '.'.

Don't abuse it though, since, as twotwotwo comments, The style guide discourages it outside of tests.

Except for this one case, do not use import . in your programs.
It makes the programs much harder to read because it is unclear whether a name like Quux is a top-level identifier in the current package or in an imported package.

That is why I mentioned a testing framework using this technique.


As commented by Simon Whitehead, using relative import is not generally considered as the best practice (see for instance "Go language package structure").

You should also import the package via the GOPATH instead of relatively, as show in "Import and not used error".

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • @SimonWhitehead true. I have edited the answer to point out that questionable import usage. – VonC Nov 08 '14 at 11:41
  • The style guide discourages it outside of tests: https://code.google.com/p/go-wiki/wiki/CodeReviewComments#Import_Dot – twotwotwo Nov 08 '14 at 22:45
  • @twotwotwo indeed. I have included your comment in the answer for more visibility. – VonC Nov 08 '14 at 22:49