rofls
rofls

Reputation: 5115

Load package contents without using their name afterwards

Is there a way to load the contents of a package in go without needing to use the package name? For example, in Python you can do:

from somepackage import *
# access function from somepackage foo
foo()

I would like to do that in Go. I tried:

import _ "path/to/my/package"

but it didn't work. I'm having trouble articulating myself to find the solution online, if there is one.

Upvotes: 2

Views: 51

Answers (1)

peterSO
peterSO

Reputation: 166626

The Go Programming Language Specification

Import declarations

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.

Use a period (.) instead of a name. For example,

package main

import (
    "fmt"
    . "time"
)

func main() {
    fmt.Println(Now()) // time.Now()
}

Output:

2009-11-10 23:00:00 +0000 UTC

Upvotes: 5

Related Questions