Golang fmt Print Function

The fmt.Print function in Golang is part of the fmt package and is used to output data to the standard output (usually the console). It formats the data using the default formats for its operands and writes them in a single line without adding any extra spaces or newlines between the operands.

Table of Contents

  1. Introduction
  2. Print Function Syntax
  3. Examples
    • Basic Usage
    • Printing Variables
  4. Real-World Use Case
  5. Conclusion

Introduction

The fmt.Print function is a simple and efficient way to display data in a Go program. It can be used to output strings, numbers, variables, or any combination of data types. Unlike fmt.Println, fmt.Print does not add a newline at the end of the output, which allows you to format your output precisely as needed.

Print Function Syntax

The syntax for the fmt.Print function is as follows:

func Print(a ...interface{}) (n int, err error)

Parameters:

  • a: The data to be printed. This can be a mix of strings, numbers, and other data types.

Returns:

  • n: The number of bytes written.
  • err: An error if one occurred during writing.

Examples

Basic Usage

This example demonstrates how to use the fmt.Print function to output text and numbers.

Example

package main

import (
	"fmt"
)

func main() {
	// Use fmt.Print to output a string and a number
	fmt.Print("The answer is ", 42)
}

Output:

The answer is 42

Printing Variables

You can use fmt.Print to print the values of variables directly.

Example

package main

import (
	"fmt"
)

func main() {
	name := "Alice"
	age := 30

	// Use fmt.Print to print variables
	fmt.Print("Name: ", name, ", Age: ", age)
}

Output:

Name: Alice, Age: 30

Real-World Use Case

Building Custom Outputs

In real-world applications, fmt.Print can be used to build custom output messages without automatic newline characters. This is useful for creating more controlled console outputs.

Example

package main

import (
	"fmt"
)

func main() {
	product := "Laptop"
	price := 999.99

	// Use fmt.Print to build a custom output message
	fmt.Print("Product: ", product)
	fmt.Print(", Price: 
quot;, price)
}

Output:

Product: Laptop, Price: $999.99

Conclusion

The fmt.Print function is a straightforward way to print data to the console without additional formatting. It is ideal for applications that require precise control over output formatting. By using fmt.Print, you can efficiently display data and messages in your Go programs.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare