Golang: Print

By Xah Lee. Date: . Last updated: .

Print

To print, load the the package fmt, then use the function fmt.Printf. Example:

fmt.Printf("there are %v apples\n", 3)

Example:
fmt.Printf("Name is %v, Age is %v \n", "john", 36)

package main

import "fmt"

func main() {

	var x = "John"
	var y = 36

	fmt.Printf("name is %v, age is %v\n", x, y)
	// name is John, age is 36

}

Printf Verbs (placeholders)

Printf Verbs converts a value to a string, in a specific format. For example: convert a integer to string type, or inter to string type but in hexadecimal form, or convert a array into a string format.

Here's the most useful verbs:

%v
Any value. Convert to a format that's human readable.
%#v
Convert it to golang syntax that represents the value.
%+v
If value is struct, also show the field names.
%T
Type of the value
%%
A literal percent sign

Complete List of Verbs

Golang: Printf Verbs

Print Line

For quick printing, use

fmt.Println(v1, v2 )

it's similar to fmt.Printf with "%v" for format.

package main

import "fmt"

func main() {

	var x = 3
	var y = 4
	fmt.Println(x, y) // 3 4
}

Example: Print Type

It is very useful to print the type of a value, when learning go.

fmt.Printf("%T\n", val)

package main

import "fmt"

// using Printf to show different types of value

func main() {

	var x = 3
	fmt.Printf("%v\n", x) // 3
	fmt.Printf("%T\n", x) // int

	var x2 = 3.4
	fmt.Printf("%v\n", x2) // 3.4
	fmt.Printf("%T\n", x2) // float64

}

Golang Print

Golang

Compile and Run

String

Types and Values

Branching and Loop

Data Structure

Function

Misc

Examples

Reference