Golang: Print

By Xah Lee. Date: . Last updated: .

Format and Print: fmt.Println

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)
    // prints
    // 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 Slice

[see Golang: Slice]

package main

import "fmt"

func main() {

    var sl = []int{3, 4, 5}

    // print it normally
    fmt.Printf("%v\n", sl) // [3 4 5]

    // print in golang syntax
    fmt.Printf("%#v\n", sl) // []int{3, 4, 5}

}

Example: Print Struct

package main

import "fmt"

// using print struct

func main() {

    type PP struct {
    x int
    y int
    }

    var stc = PP{1, 2}
    fmt.Printf("%T\n", stc)  // main.PP
    fmt.Printf("%v\n", stc)  // {1 2}
    fmt.Printf("%+v\n", stc) // {x:1 y:2}
    fmt.Printf("%#v\n", stc) // main.PP{x:1, y:2}
}

[see 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. Package, Import
  3. Comment
  4. Print
  5. String
  6. Rune
  7. Variable
  8. Zero Value
  9. Constant
  10. If Then Else
  11. Switch/Case
  12. Loop
  13. Basic Types
  14. Array
  15. Slice
  16. Map
  17. Struct
  18. Function
  19. regexp
  20. Read File
  21. Write to File
  22. Walk Dir
  23. Check File Exist
  24. System Call
  25. Pointer
  26. Defer
  27. Random Number

Examples

  1. Validate Links
  2. Generate Sitemap

Reference

  1. Go Spec