Golang print: Difference between revisions

From wikinotes
(Created page with "= Basics = <blockquote> <syntaxhighlight lang="go"> require "fmt" fmt.Println("foo") // print to stdout with newline fmt.Printf("%v", 123) // print formatted string to stdout (no newline) fmt.Fprintf(os.Stdout, "%v", 123) // prints formatted string to writable object (ex. STDOUT, STERR, ..) fmt.Sprintf("%v", 123) // returns formatted string (no newline) </syntaxhighlight> </blockquote><!-- Basics --> = Format Syntax = <blockqu...")
 
Line 29: Line 29:


# number types
# number types
%i # int
%d # int (base-10)
%f  # float
%f  # float



Revision as of 21:36, 22 July 2022

Basics

require "fmt"

fmt.Println("foo")                 // print to stdout with newline
fmt.Printf("%v", 123)              // print formatted string to stdout (no newline)
fmt.Fprintf(os.Stdout, "%v", 123)  // prints formatted string to writable object (ex. STDOUT, STERR, ..)

fmt.Sprintf("%v", 123)             // returns formatted string (no newline)

Format Syntax

Printf/Sprintf/Fprintf all take format specifiers.
See full docs here, but here's some really useful formats:

# general
%v  # value
%T  # type

# number-bases
%b  # binary
%x  # hex
%o  # octal
%d  # decimal

# number types
%d  # int (base-10)
%f  # float

# strings
%s  # string
%q  # quoted/escaped go string
%c  # unicode-char for num