Go Printing to Stdout and Stderr: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 26: Line 26:
fmt.Printf("something %s", "blue")
fmt.Printf("something %s", "blue")
</syntaxhighlight>
</syntaxhighlight>
<code>Print()</code> expects a format specifier (or a format string) as the first argument, which contains conversion characters (ex. <code>%s</code>):
<code>Print()</code> expects a '''format specifier''' (or a '''format string''') as the first argument, which contains [[Go_Package_fmt#Conversion_Characters|conversion characters]] (ex. <code>%s</code>).
===<tt>%v</tt>===
 
<code>%v</code> renders the value in a default format. When printing structs, the plus flag <code>%+v</code> adds field names.
 
<code>%#v</code> renders a Go-syntax representation of the value.
 
===<tt>%T</tt>===
 
<code>%T</code> renders a Go-syntax representation of the type of the value.
 
===Strings===
<syntaxhighlight lang='go'>
color := "blue"
fmt.Printf("The color is %s\n", color)
</syntaxhighlight>
===Integers===
<syntaxhighlight lang='go'>
size := 1
fmt.Printf("The size is %d\n", size)
</syntaxhighlight>
===Characters===
<syntaxhighlight lang='go'>
c := 'x'
fmt.Printf("The character is %c\n", c)
</syntaxhighlight>
===Booleans===
<syntaxhighlight lang='go'>
b := true
fmt.Printf("The boolean value is %t\n", b)
</syntaxhighlight>
===Floating Point Numbers===
<syntaxhighlight lang='go'>
f := 1.0
fmt.Printf("The floating point value is %f\n", f)
</syntaxhighlight>
===Pointers===
{{Internal|Pointers_in_Go#Displaying_Pointers|Pointers in Go &#124; Displaying Pointers}}
 
===Structs===
{{Internal|Go_Structs#Printing_Structs|Go Structs &#124; Printing Structs}}

Revision as of 21:56, 22 December 2023

Internal

Bootstrapping Functions

Both print() and println() are pre-declared functions, ready to use without any import.

TODO: https://golang.org/ref/spec#Bootstrapping

print()

println()

func main() {
  println("something")
}

fmt Functions

fmt.Printf()

https://golang.org/pkg/fmt/#Printf
import "fmt"

// ...
fmt.Printf("something %s", "blue")

Print() expects a format specifier (or a format string) as the first argument, which contains conversion characters (ex. %s).