golang printf and println
Printf
and Println
are two functions provided by the fmt
package in GoLang for printing formatted output and writing to standard output respectively.
Printf
:The fmt.Printf
function in GoLang allows you to format and print data to the standard output (which is usually your terminal). It's similar to printf
in other languages like C or PHP. You can use format specifiers such as %s
for strings, %d
for integers, %f
for floating point numbers, etc.
Here's an example:
package main
import "fmt"
func main() {
name := "John"
age := 30
fmt.Printf("My name is %s and I am %d years old.", name, age)
}
In this example, %s
will be replaced by the string variable name
and %d
will be replaced by the integer variable age
.
Println
:The fmt.Println
function in GoLang prints its arguments followed by a newline. It converts the variables into strings (if they aren't already) and adds a space between each argument.
Here's an example:
package main
import "fmt"
func main() {
name := "John"
age := 30
fmt.Println("My name is", name, "and I am", age, "years old.")
}
In this example, Println
will add a space between each argument and a newline at the end.
Printf
is more flexible as it allows for string formatting, however, Println
is more straightforward and easier to use when formatting isn't required.
what is ln and f mean after print
The ln
in Println
stands for line. This means that Println
will add a newline character ('\n') at the end of whatever is being printed. This will cause anything printed after a Println
statement to appear on a new line.
The f
in Printf
stands for format. This means the function will interpret the string as a format string that specifies how subsequent arguments are formatted. For example, %s
for strings, %d
for integers, and %f
for floating-point numbers.
Here's an example:
package main
import "fmt"
func main() {
name := "John"
age := 30
fmt.Printf("My name is %s and I am %d years old.", name, age)
}
In this example, %s
will be replaced by the string variable name
and %d
will be replaced by the integer variable age
.