GoLang - Print Output

2 minute read

In GoLang programming, the 'fmt' package provides a set of functions to print output to the standard output device, such as the console or terminal. Printing output is an essential aspect of any programming language as it helps in debugging, displaying information, and interacting with the user. This tutorial will guide you through the various methods of printing output in GoLang using the fmt package, along with examples.

Printing Text

To print simple text to the standard output, you can use the 'Print' function from the fmt package. Here’s an example:

package main

import "fmt"

func main() {
	fmt.Print("Hello, World!")
}

Output

Hello, World!

The 'Print' function prints the text without adding a newline character at the end.

Printing Text with a Newline: To print text followed by a newline character, you can use the 'Println' function. Here’s an example:

package main

import "fmt"

func main() {
	fmt.Println("Hello, World!")
}

Output:

Hello, World!

The 'Println' function adds a newline character at the end of the output, making it suitable for displaying multiple lines.

Printing Values: You can print the values of variables or expressions using the 'Printf' function. It allows you to specify a format string that determines how the values are displayed. Here’s an example:

package main

import "fmt"

func main() {
	name := "John"
	age := 25
	fmt.Printf("Name: %s, Age: %d\n", name, age)
}

Output:

Name: John, Age: 25

In the 'Printf' function, '%s' is used for string values, and %d is used for integer values. The values are provided after the format string, in the same order as the placeholders.

Printing with Formatting: The Printf function supports various formatting options. Here are some commonly used format verbs:

%d: Decimal integer %f: Floating-point number %s: String %t: Boolean %v: Default format (works for any value) %+v: Struct fields with field names %#v: Go syntax representation of the value %x: Hexadecimal representation (lowercase letters) %X: Hexadecimal representation (uppercase letters)

You can combine these format verbs with other formatting options like width and precision. Here’s an example:

package main

import "fmt"

func main() {
	pi := 3.14159
	fmt.Printf("Value: %.2f\n", pi)
}

Output:

Value: 3.14

In the example, %.2f specifies a floating-point number with two digits after the decimal point.

Conclusion

Printing output in GoLang is straightforward with the help of the fmt package. You can use the Print, Println, and Printf functions to display text, values, and formatted output. Understanding these methods will help you interact with users, debug code, and present information effectively. Experiment with different formatting options to customize the output according to your needs. Happy coding! Title: Understanding Print Output in Go Programming

Updated: