fmt Examples (Printf, Println)
This page was last reviewed on Jan 11, 2024.
Dot Net Perls
Fmt, printing. In Golang programs, output needs to be printed and reported. We have the "fmt" package, and many helpful funcs like Printf and Println.
Console programs. In Golang we can use Printf with a special format code. This determines how a string or integer is formatted. Println does not require a format string.
Printf, V format. To start, with Printf many format codes are available. But to make programs simpler, we can just use the "%v" format code to insert values.
And The "v" code handles ints, bools, strings and other values. It makes Printf calls easier to write and read.
package main import "fmt" func main() { result := true name := "Spark" size := 2000 // Print line with v format codes. fmt.Printf("Result = %v, Name = %v, Size = %v", result, name, size) }
Result = true, Name = Spark, Size = 2000
Other formats. We can pass various format strings to Printf. Codes like "%s" and "%d" indicate insertion points for values. Those values are also passed as arguments.
package main import "fmt" func main() { name := "Mittens" weight := 12 // Use %s to mean string. // ... Use an explicit newline. fmt.Printf("The cat is named %s.\n", name) // Use %d to mean integer. fmt.Printf("Its weight is %d.\n", weight) }
The cat is named Mittens. Its weight is 12.
Println. To continue, we examine the Println method. This method is one of the easiest and simplest ones in fmt. We first must use an import statement with the argument "fmt."
Then We invoke methods, like Println, on the fmt package. Println is versatile and can accept many arguments.
Tip We can print values like strings or ints, or more complex things like slices. No loop is needed to print elements of a slice or array.
package main import "fmt" func main() { // The Println method can handle one or more arguments. fmt.Println("cat") fmt.Println("cat", 900) // Use Println on a slice. items := []int{10, 20, 30} fmt.Println(items) }
cat cat 900 [10 20 30]
Print, for-loop. The Println always inserts a newline after we use it. But Print does not: it just writes the data to the console with no trailing newline.
Tip For loops where we want to display many things on a single line, Print is ideal.
package main import "fmt" func main() { elements := []int{999, 99, 9} // Loop over the int slice and Print its elements. // ... No newline is inserted after Print. for i := 0; i < len(elements); i++ { fmt.Print(elements[i] + 1) fmt.Print(" ") } fmt.Println("... DONE!") }
1000 100 10 ... DONE!
Print, println. Print and println are universal functions. We can call these without referencing the "fmt" package. But their functionality is not identical to the fmt methods.
Warning Idiomatic Go tends to use fmt.Println not just println. The fmt package is thus preferred.
package main func main() { value := 10 // Use println. println(value) // Use print. // ... Use println with no arguments to write a newline. print(value) println() // Done. println("DONE") }
10 10 DONE
Println differences. The println universal function has different output than the fmt.Println method. They are not the interchangeable.
Here Consider a slice of two ints. Fmt.Println displays the elements, but "println" displays a reference value.
package main import "fmt" func main() { items := []int{10, 20} // These two println methods have different output. fmt.Println(items) println(items) }
[10 20] [2/2]0xc08200a250
Sprintf. This method is a string-based form of Printf. The "S" stands for "string." So we use Printf and it returns a string—the value is not written to the console.
Here We use 2 formats (the "%v" handles any value) to compose 1 string. We then print its length, and its contents with fmt.Println.
Tip If we want to store the results of Printf in a string (for later use or processing) then Sprintf is ideal.
import "fmt" func main() { value1 := "a tree"; value2 := "the park"; // Use format string to generate string. result := fmt.Sprintf("I saw %v at %v.\n", value1, value2) // Write length of string, and string itself. fmt.Println("Length:", len(result)) fmt.Println(result) }
Length: 26 I saw a tree at the park.
Sprintln. This func takes any number or arguments—it works the same way as fmt.Println, but returns a string. It does not support format codes.
package main import "fmt" func main() { // Use Sprintln, no format strings are supported. // ... A newline is added. // A string is returned. result := fmt.Sprintln("Hey friend", 100) fmt.Print("[" + result + "]") }
[Hey friend 100 ]
Fprint, Fprintf. These methods are just like fmt.Print but target a file in the first argument. They write to files—nothing is written to the console.
Sscan, Sscanf. We can parse in space-separated values with fmt.Sscan. And with Sscanf we use a format string to parse in values. Sometimes this is easier than using split() or fields().
Padding. We can apply padding with fmt.Printf to ensure strings are a certain number of characters long. Spaces are added before or after the value.
String Padding
A review. With methods prefixed by s, we can output the results to a string. We can write those strings to a file, or use them in any way we can use a string.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 11, 2024 (edit).
© 2007-2024 Sam Allen.