这是我参与「第三届青训营 -后端场」笔记创作活动的的第1篇笔记 Go语言基础--命令式编程
- 格式化输出
- fmt.Print
- fmt.Println
- fmt.Printf
package main
import "fmt"
// main 是所有程序的起始函数
func main() {
fmt.Print("My weight on the surface of Mars is ")
fmt.Print(149.0 * 0.3783)
fmt.Print(" lbs, and I would be ")
fmt.Print(41 * 365 / 687)
fmt.Print(" years old.")
}
fmt.Println("My weight on the surface of Mars is", 149.0*0.3783, "lbs, and I would be",
41*365.2425/687, "years old.")
fmt.Printf("My weight on the surface of Mars is %v lbs,", 149.0*0.3783)//单个变量
fmt.Printf(" and I would be %v years old.\n", 41*365/687)
fmt.Printf("My weight on the surface of %v is %v lbs.\n", "Earth", 149.0)//多个变量
- 变量
- const:常量
- var:变量 声明:
const hoursPerDay = 24
var distance = 56000000
var speed = 100800
var (
distance = 56000000
speed = 100800
)
var distance, speed = 56000000, 100800
注:支持i++ 不支持++i
- 随机数: 引包:"math/rand" 使用:rand.Intn(10)
package main
import (
"fmt"
"math/rand"
)
func main() {
var num = rand.Intn(10) + 1
fmt.Println(num)
num = rand.Intn(10) + 1
fmt.Println(num)
}
- 循环和分支
- 布尔
var a = true
var b = false
var command = "walk outside"
var exit = strings.Contains(command, "outside")
- if
if strs == "abd" {
fmt.Println("sss")
} else {
fmt.Println("asdad")
}
- switch
var command = "1"
switch command {
case "1":
fmt.Println("You head further up the mountain.")
case "2":
fmt.Println("You find yourself in a dimly lit cavern.")
case "3":
fmt.Println("The sign reads 'No Minors'.")
default:
fmt.Println("Didn't quite get that.")
}
fallthrough关键字:
var room = "lake"
switch {
case room == "cave":
fmt.Println("You find yourself in a dimly lit cavern.")
case room == "lake":
fmt.Println("The ice seems solid enough.")
fallthrough//跳到下一个选择
case room == "underwater":
fmt.Println("The water is freezing cold.")
}
- for
var count = 10
for count > 0 {
fmt.Println(count)
time.Sleep(time.Second)
count--
}
fmt.Println("Liftoff!")
for count := 10; count > 0; count-- {
fmt.Println(count)
}