I'm going to write the understanding of Go from the basics of programming! Click here for Go language basics ❶ Click here for Go language basics ❷
Go has what is called a standard package, which has more than 100 useful functions. Prepared from the beginning You are free to use these in your program
Can output to the fmt console
math/rand Can generate random numbers
time Can process time
package main
import "fmt" //Import standard package
Import is described as "import" package name "" under "package main"
package main
import "fmt"
func main() {
fmt.Println("Hello,Go")
}
//console
Hello,Go
"Fmt.Println" can display more data types than "println"
package main
import "fmt"
func main() {
Println("Hello,Go") //Not using fmt package
}
//console
Error if fmt package is not used
If you are importing the fmt package but not using it, you will get an error
fmt.Printf
fmt.Printf(Format,Value used for output)
You can use the Printf function of the fmt package to specify the format and output it to the console.
The format is the shape of the output character string. Specify the format first and the value used for output second
func main() {
name := "Tanabe"
fmt.Printf("Hello,%s", name) //%The character string contained in the variable name is used for s
}
//console
Hello,Mr. Tanabe
If you include% s in a string like "Hello,% s" The second specified character string of "fmt.Printf" is inserted in the% s part and output.
func main() {
name := "Tanabe"
fmt.Printf("%s, %s","Hello", name)
}
//console
Hello,Mr. Tanabe
When using% s twice, it is necessary to specify the character string to be inserted in each% s
func main() {
age := 26
fmt.Printf("%d years old", age)
}
//console
26 years old
You can insert numbers as well as strings in the format % D in case of numerical value
func main() {
age := "26"
fmt.Printf("%d years old", age)
}
//console
%!d(string=26)I'm old//On the form%Error because d is used
You can insert numbers as well as strings in the format % D in case of numerical value
func main() {
fmt.Printf("Hello,% S", "Tanabe")
fmt.Printf("Hello, %s", "Naito")
}
//console
Hello,Tanabe Hello,Mr. Naito
"Fmt.Printf" is different from "fmt.Println" Does not start a new line after the output string
\n
func main() {
fmt.Printf("Hello, %s\n", "Tanabe")
fmt.Printf("Hello, %s\n", "Naito")
}
//console
Hello,Mr. Tanabe
Hello,Mr. Naito
If you use \ n in a string, the output string will break.
\n(2)
func main() {
name := "Tanabe"
fmt.Printf("Hello, \n%s" name) //In the text\Include n
}
//console
Hello,
Mr. Tanabe
If you include it in the middle of the string, the character following \ n will be broken and output to the next line.