Golang: Print

By Xah Lee. Date: . Last updated: .

Format and Print: fmt.Printf

Use the package fmt

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

The first argument is a string. The string can contain many special placeholder characters , starting with the percent character % (U+25: PERCENT SIGN)

2nd argument and rest arguments are used to fill the placeholders.

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

}

Here's the most useful placeholders:

Print Line: fmt.Println

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
}

Format to String

To convert a value to string, use

fmt.Sprintf(string, v1, v2 …)

it return a string instead of printing.

package main

import "fmt"

func main() {

	var x = "John"
	var y = 36

	var s = fmt.Sprintf("name is %v, age is %v\n", x, y)

	fmt.Println(s == "name is John, age is 36\n") // true
}

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

}

Example: Print String

Golang: Print String

Example: Print Slice

Golang: Slice

Example: Print Struct

Golang: Struct

Print String, as Bytes, Character, Codepoint

see Golang: String

Reference

https://golang.org/pkg/fmt/

If you have a question, put $5 at patreon and message me.

Golang

  1. Compile, Run
  2. Source Encoding
  3. Package, Import
  4. Comment
  5. Print
  6. String
  7. Print String
  8. String Backslash Escape
  9. Rune
  10. Variable
  11. Zero Value
  12. Constant
  13. If Then Else
  14. Switch/Case
  15. Loop
  16. Basic Types
  17. Array
  18. Slice
  19. Map
  20. Struct
  21. Function
  22. Closure
  23. Pointer
  24. String, Byte Slice, Rune Slice
  25. regexp
  26. Read File
  27. Write to File
  28. Walk Dir
  29. Check File Exist
  30. System Call
  31. Get Script Path
  32. Defer
  33. Random Number

Examples

  1. Match Any Regexp
  2. Find Replace
  3. Validate Links
  4. Generate Sitemap

Reference

  1. Go Spec