Golang input/output: Difference between revisions

From wikinotes
(Created page with "= print = <blockquote> == Basics == <blockquote> <syntaxhighlight lang="go"> require "fmt" fmt.Println("foo") // print to stdout with newline fmt.Printf("%v",...")
 
Line 14: Line 14:
</blockquote><!-- Basics -->
</blockquote><!-- Basics -->


== Printf ==
== Format Syntax ==
<blockquote>
<blockquote>
Printf is super useful for introspection in go.<br>
Printf/Sprintf/Fprintf all take format specifiers.<br>
See full docs [https://pkg.go.dev/fmt@go1.18.2 here], but here's some really useful formats:
See full docs [https://pkg.go.dev/fmt@go1.18.2 here], but here's some really useful formats:



Revision as of 19:12, 29 May 2022

print

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
%i  # int
%f  # float

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