文件名称 | 版本号 | 作者 | 版本 | |
---|---|---|---|---|
go语言就是golang_1天学会_基础篇 | v1.0.2 学生宫布 | 8416837 | go1.13.4 windows/amd64 |
go环境-vscode
基础、web等
go web代码生成、基于框架开发
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("hg")
fmt.Println("Time", time.Now())
}
// 【注意】必须是"2006-01-02 15:04:05",否则格式化不正确
fmt.Println("Time", time.Now().Format("2006-01-02 15:04:05"))
fmt.Println("Time", now.Year())
package main
import (
"fmt"
"strings"
)
func main() {
var strs [3]string
strs[0] = "6e0ef25a-32f1-4405-b458-efbde3ff4ec6"
strs[1] = "ae632042-1b77-4fd5-b76a-7ac730db8a6c"
strs[2] = "204b7324-4ee4-4672-9900-faa8ee392432"
replacer := strings.NewReplacer("-", "")
for i := 0; i < len(strs); i++ {
fmt.Println(replacer.Replace(strs[i]))
}
}
package main
import (
"container/list"
"fmt"
)
func main() {
table := list.New()
table.PushBack(1)
table.PushBack("ball")
table.PushBack("orange")
table.PushBack('x')
table.PushFront(88.48)
fmt.Println("长度", table.Len())
for i := table.Front(); i != nil; i = i.Next() {
// 末尾i变成nil
fmt.Println(i.Value)
}
}
package main
import (
"fmt"
"time"
)
func doSth(msg string, NUM int) {
for i := 0; i < NUM; i++ {
time.Sleep(123 * time.Millisecond)
fmt.Println(msg)
}
}
func main() {
go doSth("goroutine~", 5)
doSth("main thread~", 5)
}
package main
import "fmt"
func sum(s []float32, compute_channel chan float32) {
// chan float32 定义通道
var sum float32 = 0
for _, v := range s {
sum += v
}
compute_channel <- sum // 把 sum 发送到通道 compute_channel
}
func main() {
s := []float32{
3.5, 9.2, 0.3, 5, 5, 0} // 定义输入
compute_channel := make(chan float32)
go sum(s[:len(s)/2], compute_channel) // 多个goroutine模拟分布式计算 当前场景各计算一半
go sum(s[len(s)/2:], compute_channel) // go命令执行后,开始并发
x1, x2 := <-compute_channel, <-compute_channel // 从通道 compute_channel 中接收
fmt.Println(x1, x2, x1+x2)
}
package main
import (
"errors"
"fmt"
)
func Sqrt(f float64) (float64, error) {
// 多个返回
if f < 0 {
return 0, errors.New("math: square root of a negative number is not permitted")
}
// 模拟实现
return 1, nil // 返回多个
}
func main() {
val,err := Sqrt(-1)
if err != nil {
fmt.Println(`结果 == `, val, `
异常 == `, err)
}
}
结果 == 0
异常 == math: square root of a negative number is not permitted
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
func main() {
var targetNum float64 = 100
var num float64
var msg string
var count int
for {
fmt.Println("Please input one number")
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
input = strings.TrimSpace(input)
count++
num, err = strconv.ParseFloat(input, 64)
if err != nil {
log.Fatal(err)
}
if num == targetNum {
fmt.Println(count, `真棒,猜对了`)
break
} else if num > targetNum {
msg = `大了`
} else if num < targetNum {
msg = `小了`
}
fmt.Println(`输入`, num, msg, `第`, count, `次竞猜`)
}
}