Go Printing to Stdout and Stderr: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 18: Line 18:


// ...
// ...
fmt.Printf("something")
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>):
==Format Strings==
===Strings===
The format strings contain conversion characters (ex. <code>%s</code>):
<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'>
<syntaxhighlight lang='go'>
fmt.Printf("Hello %s", "Bob")
b := true
fmt.Printf("The boolean value is %t\n", b)
</syntaxhighlight>
</syntaxhighlight>
Prints according to a format specifier. Format specifier documentation https://golang.org/pkg/fmt
===Pointers===
===Pointers===
 
<syntaxhighlight lang='go'>
<pre>
s := "something"
fmt.Printf("%p\n", sPtr)
sPtr := &s
</pre>
fmt.Printf("pointer value: %p\n", sPtr)
</syntaxhighlight>


"%p" prepend the "0x" prefix.
"%p" prepend the "0x" prefix.


Pointers can be also represented using "%X" (base 16, upper case characters).
Pointers can be also represented using "%X" (base 16, upper case characters).
===Ints===
<pre>
fmt.Printf("%d\n",i)
</pre>
===Characters===
<pre>
fmt.Printf("%c\n",i)
</pre>
===Boolean Values===
<pre>
fmt.Printf("%t\n",b)
</pre>

Revision as of 01:01, 19 August 2023

Internal

Bootstrapping Functions

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

print()

println()

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

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):

Strings

color := "blue"
fmt.Printf("The color is %s\n", color)

Integers

size := 1
fmt.Printf("The size is %d\n", size)

Characters

c := 'x'
fmt.Printf("The character is %c\n", c)

Booleans

b := true
fmt.Printf("The boolean value is %t\n", b)

Pointers

s := "something"
sPtr := &s
fmt.Printf("pointer value: %p\n", sPtr)

"%p" prepend the "0x" prefix.

Pointers can be also represented using "%X" (base 16, upper case characters).