8

Suppose I get bored in typing System.out.println(message) in all the places, I introduce a method in java that looks like

private void print (Object message) {
   System.out.println(message);
}

and I call print (2) & print ("hi") in java wherever necessary .

Can the same be achieved in GoLang too ? A function something like this

func print(message ) {
    fmt.Println (message)
}
Arun
  • 3,440
  • 11
  • 60
  • 108
  • 2
    ... and interface{}. Just do what fmt.Println() does as you obviously want your keystrokesaver to behave like Println() so use the same signature. – Volker Oct 17 '18 at 09:33

2 Answers2

8

Go is a procedural programming language with many functional programming elements.

Functions are first-class types in Go, you can create variables of function type, and you can assign function values to these variables, and you can call them (the function value stored in them).

So you may simply do:

var myprint = fmt.Println

myprint("Hello, playground")
myprint(1, 3.14, "\n", time.Now())

Output of the above (try it on the Go Playground):

Hello, playground
1 3.14 
 2009-11-10 23:00:00 +0000 UTC m=+0.000000001

The advantage of the above myprint variable is that it will have the same signature as fmt.Println(), which is:

func Println(a ...interface{}) (n int, err error)

Yes, we can also create a wrapper function like:

func myprint(a ...interface{}) (n int, err error) {
    return fmt.Println(a...)
}

And it will work the same as calling fmt.Println(), but using a variable is less verbose, and it has the advantage that you can change the function value at runtime, which is very handy when writing tests (for an example, see Testing os.Exit scenarios in Go with coverage information (coveralls.io/Goveralls)).

More on the topic:

Dave Cheney: Do not fear first class functions

golangbot.com: First Class Functions

Yet another possibility is to use "dot import", but I advise against it:

import (
    . "fmt"
)

func main() {
    Println("Hello, playground")
}

When you use a "dot import", all exported identifiers of the imported package become accessible without having to use qualified identifiers. Quoting from Spec: 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.

icza
  • 389,944
  • 63
  • 907
  • 827
4

Have you tried using interface ?

func print(obj interface{}) {
 // logic
}

This way you can accept whatever you want.

Tomasz Bawor
  • 1,447
  • 15
  • 40