Go Print Statement
In Go, you can use the fmt
package to print values to the console. Here's how you can use the fmt.Println
function to print a value to the console:
package main import "fmt" func main() { fmt.Println("Hello, world!") }
The fmt.Println
function takes one or more arguments and prints them to the console, separated by spaces. It also adds a newline character at the end of the output, so each call to Println
prints its output on a new line.
You can also use the fmt.Printf
function to print values using a format string. A format string is a string that specifies how to format the values you want to print. Here's an example:
package main import "fmt" func main() { name := "Alice" age := 30 fmt.Printf("Name: %s, Age: %d\n", name, age) }
In this example, we're using the %s
and %d
format specifiers to print the values of the name
and age
variables, respectively. The \n
character at the end of the format string adds a newline character to the output.
You can also use the fmt.Sprintf
function to format values as a string, without printing them to the console. This can be useful if you need to store the formatted string in a variable or pass it to another function. Here's an example:
package main import "fmt" func main() { name := "Bob" age := 25 str := fmt.Sprintf("Name: %s, Age: %d", name, age) fmt.Println(str) }
In this example, we're using the fmt.Sprintf
function to format the values of the name
and age
variables into a string, and then printing the resulting string to the console using fmt.Println
.