An overview of the

Print is defined in the FMT package to format a string and write standard output.

https://golang.org/pkg/fmt/#Print
Copy the code

Here is the prototype function for Print

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

Print uses the default format specifier to format the string, but does not add a new line after the string. Print takes a variable number of arguments, each of which is a null interface. It returns the number of characters printed and any errors (if they occur). Since the parameter type is an empty interface, we can pass any data type to it. We can pass a string, int, float, struct, or any other data type. Each argument to the Print function is formatted according to the default format specifier for that parameter type. For example, the structure will be formatted according to the following format specifier

%v
Copy the code

The format specifier prints only the value part of the structure. The FMT package also provides a function called Println that appends a new line. The Print function is exactly the same as the Println function, with two differences

  • It doesn’t add a line break at the end. We need to use the newline identifier to add a new line “/n”.

  • Spaces are added between arguments only if none of the operands is a string

Let’s look at an example

The program

Let’s look at a similar example

package main

import "fmt"

type employee struct {
	Name string
	Age  int
}

func main(a) {
	name := "John"
	age := 21
	fmt.Print("Name is:", name, "\n")
	fmt.Print("Age is:", age, "\n")

	e := employee{
		Name: name,
		Age:  age,
	}

	fmt.Print(e, "\n")

	fmt.Print("a".12."b".12.0."\n")

	fmt.Print(12.12.0."\n")
        
        
        bytesPrinted, err := fmt.Print("Name is: ", name, "\n")
	iferr ! =nil {
		log.Fatalln("Error occured", err)
	}
	fmt.Print(bytesPrinted)
}
Copy the code

The output

Name is:John
Age is:21
{John 21}
a12b12
12 12
Name is: John
14
Copy the code

A few points to note about the Print function

  • It doesn’t append a new line at the end. This is why you need to use **”\n “to ** add a new line.

  • It only adds Spaces between two arguments if each argument is a non-string. That’s why

fmt.Print(12.12.0."\n")
Copy the code

print

12 12
Copy the code

while

fmt.Print("a".12."b".12.0."\n")
Copy the code

print

a12b12
Copy the code
  • It also returns the number of characters printed and any errors if they occur
bytesPrinted, err := fmt.Print("Name is: ", name, "\n")
iferr ! =nil {
    log.Fatalln("Error occured", err)
}
fmt.Print(bytesPrinted)
Copy the code

The following output is displayed

Name is: John
14
Copy the code

The number of bytesPrinted is 14, because the output is 14 characters.

Also, check out our Golang Advanced Tutorials series -Golang Advanced Tutorials

The postUnderstanding Print function in Go (Golang)appeared first onWelcome To Golang By Example.