Functions
Guide to functions for printing in Go
Overview
Println
Print with default formatting.
Spaces are always added between operands and a newline is appended.
name := "World"
fmt.Println("Hello", name)
// Hello Gopher
In Python:
name = "World"
print("Hello", name)
Equivalent in JS:
name = "World"
console.log("Hello", name");
Same as Println
, except without the newline.
e.g.
name := "World"
fmt.Print("Hello", name)
fmt.Print("Goodbye", name)
// Hello GopherGoodbye Gopher
Printf
Print with formatting specifier. See more info in Format.
Note use of %v
to substitute variable inside the string.
Remember to add the newline character yourself.
name := "World"
fmt.Printf("Hello %v!\n", name)
// Hello, World!
The printf
name also used in C and Bash.
Equivalent in Python:
name = "World"
print(f"Hello {name}")
Equivalent in JS:
name = "World"
console.log(`Hello ${name}`);
You can use Printf
without any variables, but you have to remember to add the newline so then you are probably better off using Println
.
fmt.Printf("Hello\n")
// Hello
Sprintf
This formats a string and returns it, without actually printing it.
From the docs:
func Sprintf(format string, a ...interface{}) string
Sprintf formats according to a format specifier and returns the resulting string.
package main
import (
"fmt"
"io"
"os"
)
func main() {
const name, age = "Kim", 22
s := fmt.Sprintf("%s is %d years old.\n", name, age)
io.WriteString(os.Stdout, s)
}
Fprintln
Print to an io.Writer
instance.
e.g.
fmt.Fprintln(os.Stdout, e)
fmt.Fprintln(os.Stdout, "a", 12, "b", 12.0)
Fprint
As above but without newline.