In go, if we want to print something, we can do so as follows:
import "fmt"
func main(){
fmt.Println("Hello world!")
}
But I found that one can do the same without importing fmt
:
func main(){
println("Hello world!")
}
Could someone please explain?
println
is an built-in function (into the runtime) which may eventually be removed, while thefmt
package is in the standard library, which will persist. See the spec on that topic.For language developers it is handy to have a
println
without dependencies, but the way to go is to use thefmt
package or something similar (log
for example).As you can see in the implementation the
print(ln)
functions are not designed to even remotely support a different output mode and are mainly a debug tool.As for the difference, this is an example.
println()
prints a pointer point to the address of function test.fmt.Println()
prints the address of function.To build upon nemo's answer:
println
is a function built into the language. It is in the Bootstrapping section of the spec. From the link:Thus, they are useful to developers, because they lack dependencies (being built into the compiler), but not in production code. It also important to note that
print
andprintln
report tostderr
, notstdout
.The family provided by
fmt
, however, are built to be in production code. They report predictably tostdout
, unless otherwise specified. They are more versatile (fmt.Fprint*
can report to anyio.Writer
, such asos.Stdout
,os.Stderr
, or even anet.Conn
type.) and are not implementation specific.Most packages that are responsible for output have
fmt
as a dependency, such aslog
. If your program is going to be outputting anything in production,fmt
is most likely the package that you want.