expose a function in go package

You need to get your structure currently .. I want to assume your content is in src folder

src/main.go

package main

import (
    "fmt"
    "./mypackage"
)

func main() {
    var value mypackage.Export
    value.DoMagic()
    fmt.Printf("%s", value)

}

src/mypackage/export.go

package mypackage

import "fmt"

type Export struct {
}

func (c Export) DoMagic() {
    fmt.Println("Magic function was called")
}

func (c Export) String() string {
    return fmt.Sprint("ta da! \n")
}

Run go run main.go you would get

Magic function was called
ta da!

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 ;)


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)    
}

Tags:

Go