Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expose a function in go package

Tags:

go

I would like to expose a function directly from a package.
So I could call my package directly instead of mypackage.Somepublic() method.

package main

import (
    "mypackage"
    "fmt"
)

func main() {
    var result = mypackage() 
    fmt.Println(result)    
}

In node.js, for example, you can expose a anonymous function

module.export = function() {
    console.log('ta da!');
}

or an object

module.export = {  
    doMagic: function() {  
        console.log('ta da!');
    }
};
like image 798
alfonsodev Avatar asked Aug 02 '13 09:08

alfonsodev


People also ask

How do I use a function from another package in go?

The function to be used in another package must start with a capital letter i.e func Fullname(element,element2 string) string{} , so that it will be public outside its package. Once defined using the lower case syntax i.e func fullName()string{} its only accessible with thin that package.

How do you call a main function in go?

main() function It does not take any argument nor return anything. Go automatically call main() function, so there is no need to call main() function explicitly and every executable program must contain single main package and main() function.

How do you access a struct from an external package in go?

Create a file father.go inside the father folder. The file inside the father folder should start with the line package father as it belongs to the father package. The init function can be used to perform initialization works and can also be used to confirm the correctness of the program before the execution begins.


2 Answers

While there is no direct analogy for your Node.js example, what you can do in Go is something called a "local import." Basically, a local import imports all of the items - functions, types, variables, etc - that a package exports into your local namespace so that they can be accessed as if they had been defined locally. You do this by prefacing the package name with a dot. For example:

import . "fmt"

func main() {
    Println("Hello!") // Same as fmt.Println("Hello!")
}

(See this in action).

This will work for any item that fmt exports. You could do a similar thing with mypackage (this is modified from the code you posted):

package main

import (
    . "mypackage"
    "fmt"
)

func main() {
    var result = Somepublic() // Equivalent to mypackage.Somepublic()
    fmt.Println(result)    
}
like image 160
joshlf Avatar answered Oct 21 '22 22:10

joshlf


Quoting the answer of mko here for better visibility:

Dear Lonely Anonymous adventurer. I guess you got here for the same reason I did. So, the basic answer is. Use capital letter in the name ;) source: tour.golang.org/basics/3 - yes, I was surprised as well. I was expecting some fancy stuff, but that's all it is. Capital letter - export, small letter - no export ;)

like image 21
JaM Avatar answered Oct 22 '22 00:10

JaM