Go Printing to Stdout and Stderr: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 61: Line 61:
Pointers can be also represented using <code>"%X"</code> (base 16, upper case characters).
Pointers can be also represented using <code>"%X"</code> (base 16, upper case characters).
===Structs===
===Structs===
The entire structure, including the field names and values, can be printed with <code>%+v</code>format specifier:
The entire [[Go_Structs#Printing_Structs|structure]], including the field names and values, can be printed with <code>%+v</code> format specifier:
<syntaxhighlight lang='go'>
<syntaxhighlight lang='go'>
i := Item{"blue", 1}
i := Item{"blue", 1}
fmt.Printf("i: %+v\n", i)
fmt.Printf("i: %+v\n", i)
</syntaxhighlight>
</syntaxhighlight>

Revision as of 02:00, 25 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 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):

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)

Floating Point Numbers

f := 1.0
fmt.Printf("The floating point value is %f\n", f)

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

Structs

The entire structure, including the field names and values, can be printed with %+v format specifier:

i := Item{"blue", 1}
fmt.Printf("i: %+v\n", i)