An overview of the

Println is defined in the FMT package and is used to format strings and write standard output

Golang.org/pkg/fmt/#Pr…

Here’s the prototype of the Println function

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

Println formats the string using the default format specifier and adds a new line after the string. Println takes a variable number of arguments, each of which is an empty 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 Println 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. Let’s look at an example

The program

package main
import "fmt"
type employee struct {
    Name string
    Age  int
}
func main(a) {
    name := "John"
    age := 21
    fmt.Println("Name is: ", name)
    fmt.Println("Age is: ", age)
    e := employee{
        Name: name,
        Age:  age,
    }
    fmt.Println(e)
    fmt.Println("a".12."b".12.0)

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

The output

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

Now, a couple of things to notice about Println

  • It appends a newline at the end. That’s why each output is on a different line.

  • Each parameter is separated by a space in the output. That’s why

fmt.Println("Name is: ", name)
Copy the code

print

Name is: John
Copy the code

Spaces are automatically introduced between the two parameters.

  • It returns the number of characters printed or any errors (if any).
bytesPrinted, err := fmt.Println("Name is: ", name)
iferr ! =nil {
    log.Fatalln("Error occured", err)
}
fmt.Println(bytesPrinted)
Copy the code

The following output is displayed

Name is: John
14
Copy the code

The number of bytesPrinted is 14, because 14 characters are printed.

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

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