banner
LAPLACE

王友元's blog

停下来前一定要想好下次开始时需要做的事情
telegram
x
email

Golang Study Notes - Basic Function Usage and Variable Declaration

print#

fmt.Printf

  • Printf is an abbreviation for "print formatted"
  • Printf is used to create formatted output
  • Printf does not automatically add a newline character, so you need to add \n or other characters yourself to control line breaks.
  • Printf needs to use placeholders (such as %s, %d, %f, etc.) to specify the format of the output text and provide the corresponding values.

Println

  • Println is an abbreviation for "print line"
  • It is used to print text and add a newline character at the end, with the output content on different lines.
  • Println does not require a formatted string or placeholders.

Example:

package main

import "fmt"

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

	// Use Printf for formatted output
	fmt.Printf("Name: %s Age: %d\n", name, age)

	// Use Println for output
	fmt.Println("Name:", name, "Age:", age)
}

// Output
// Name: Alice Age: 30
// Name: Alice Age: 30

Note#

In exported names, the first letter needs to be capitalized. In other words, if a name starts with a capital letter, it is exported.

For example,
fmt.Printf is allowed
fmt.printf is not allowed (Printf needs to be capitalized)

Example:

import (
	"fmt"
	"math"
)

func main() {
	fmt.Println(math.Pi) // Both math.Pi and fmt.Println need to be capitalized
}

Example of using a function:

package main

import "fmt"

func main() {
	a := 3
	b := 5
	// Use Println to output data
	fmt.Println("a is", a, "sum is", sum(a, b))
	// Use Printf to output data
	fmt.Printf("a is %d , sum is %d", a, sum(a, b))
}

// Return a value (sum) by specifying a single return parameter type
// func function_name(input_parameter, input_parameter variable_type) (return_type return_type) {
// Function body
//}
func sum(x, y int) int {
	return x + y
}

Variable Declaration#

Use a := "azusa" to quickly declare a variable a with a value of type string. You do not need to manually set the variable type (note that string types need quotation marks). := structure cannot be used outside of a function.

a := "azusa"
b := 123

is equivalent to

var a string = "azusa"
var b int = 123

More examples:

var i, j int = 1, 2
var c, p, j = true, false, "no!"
// c and p are of type bool, j is of type string

var will also automatically determine the variable type.

Variable declarations without an explicit initial value are assigned their zero value.#

The zero values are:
numeric types are 0,
boolean types are false,
strings are "" (empty string).

...

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.