The Question is simple - how can i implement a package independent global function in golang.
ID, if i have a function in an package called core then from another package i need core.Function() to call that function. But i In go implementation there are some functions like - make(), append() for slice that can used without any import and within any package directly. If i wanted to write function like this what is the way of doing this? how can i write any function like this if it is possible.
It's not possible to do exactly what you want but you can get somewhat close to it by using a dot-import. E.g. if you dot-import the fmt
package, you can spell fmt.Println
as just Println
:
package main
import . "fmt"
func main() {
Println("Hello, playground")
}
Playground: http://play.golang.org/p/--dWV6PHYA.
The short answer is: you can't. Go has builtin functions and types, but even the language designers try to keep their number to a minimum and avoid them if possible. For instance, there is a builtin printf
function, but it is recommended to use fmt.Printf
instead, as the builtin function "is not guaranteed to stay in the language".
While having to prepend the package name every time you use a function may appear cumbersome, it has its obvious advantages (makes code easier to read, avoids name collisions) and isn't actually as bad as it sounds if the package designer followed the guidelines described under "Naming package contents" in this blog post.
Example: to create a Regexp
object from a pattern string, you call regexp.Compile()
, not regexp.CompileRegexp()
- since you use the package name when calling a function, the name of the function can be shortened. This is of course lost if you use the "dot import" as per Ainar-G's suggestion. Then you would have just Compile()
, which might be confusing ("compile what?").