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!');
}
};
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.
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.
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.
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)
}
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With