A-D
package main
import "fmt"
func main() {
//创建int型数组a,大小为5,数组内默认值为0
var a [5]int
fmt.Println("emp:", a)
//对int数组a的索引为4的元素赋值为100
a[4] = 100
fmt.Println("set:", a)
fmt.Println("get:", a[4])
//判定长度
fmt.Println("len:", len(a))
//采用短变量声明一个int数组b,并指定相应位置的值
b := [5]int{1, 2, 3, 4, 5}
fmt.Println("dcl:", b)
//与b的创建一样,初始为空数组,大小5
c := [5]int{}
fmt.Println("c:", c)
//创建二维数组 默认为空
var twoD [2][3]int
for i := 0; i < 2; i++ {
for j := 0; j < 3; j++ {
twoD[i][j] = i + j
}
}
fmt.Println("2d: ", twoD)
}
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var ops uint64
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(1)
go func() {
for c := 0; c < 1000; c++ {
atomic.AddUint64(&ops, 1)
}
wg.Done()
}()
}
wg.Wait()
fmt.Println("ops:", ops)
}
package main
import (
b64 "encoding/base64"
"fmt"
)
func main() {
data := "abc123!?$*&()'-=@~"
//对字符串进行
sEnc := b64.StdEncoding.EncodeToString([]byte(data))
fmt.Println(sEnc)
sDec, _ := b64.StdEncoding.DecodeString(sEnc)
fmt.Println(string(sDec))
fmt.Println()
uEnc := b64.URLEncoding.EncodeToString([]byte(data))
fmt.Println(uEnc)
uDec, _ := b64.URLEncoding.DecodeString(uEnc)
fmt.Println(string(uDec))
}
package main
import "fmt"
func main() {
messages := make(chan string, 2)
messages <- "buffered"
messages <- "channel"
fmt.Println(<-messages)
fmt.Println(<-messages)
}
package main
import "fmt"
func ping(pings chan<- string, msg string) {
pings <- msg
}
func pong(pings <-chan string, pongs chan<- string) {
msg := <-pings
pongs <- msg
}
func main() {
pings := make(chan string, 1)
pongs := make(chan string, 1)
ping(pings, "passed message")
pong(pings, pongs)
fmt.Println(<-pongs)
}
package main
import (
"fmt"
"time"
)
func worker1(done chan bool) {
fmt.Print("working...")
time.Sleep(time.Second)
fmt.Println("done")
done <- true
}
func main() {
done := make(chan bool, 1)
go worker1(done)
//<-done
}
package main
import "fmt"
func main() {
//通道(channels) 是连接多个协程的管道。 你可以从一个协程将值发送到通道,然后在另一个协程中接收。
//使用 make(chan val-type) 创建一个新的通道
messages := make(chan string)
//channel(messages) <- string 发送一个值到通道中
go func() { messages <- "ping" }()
//从通道中 接收一个值
//变量 := <-channel
msg := <-messages
fmt.Println(msg)
}
package main
import "fmt"
func main() {
jobs := make(chan int, 5)
done := make(chan bool)
go func() {
for {
j, more := <-jobs
if more {
fmt.Println("received job", j)
} else {
fmt.Println("received all jobs")
done <- true
return
}
}
}()
for j := 1; j <= 3; j++ {
jobs <- j
fmt.Println("sent job", j)
}
close(jobs)
fmt.Println("sent all jobs")
<-done
}
package main
import "fmt"
func intSeq() func() int {
//函数式编程,可以参考《计算机程序构造与解释》一书(Lisp)
i := 0 //----1
return func() int {
i++ //----2
return i //----3
}
}
func main() {
nextInt := intSeq()
fmt.Println(nextInt())
fmt.Println(nextInt())
fmt.Println(nextInt())
newInts := intSeq()
fmt.Println(newInts())
}
package main
import (
"fmt"
"os"
)
func main() {
argsWithProg := os.Args
argsWithoutProg := os.Args[1:]
arg := os.Args[3]
fmt.Println(argsWithProg)
fmt.Println(argsWithoutProg)
fmt.Println(arg)
}
package main
import (
"flag"
"fmt"
)
func main() {
wordPtr := flag.String("word", "foo", "a string")
numbPtr := flag.Int("numb", 42, "an int")
forkPtr := flag.Bool("fork", false, "a bool")
var svar string
flag.StringVar(&svar, "svar", "bar", "a string var")
flag.Parse()
fmt.Println("word:", *wordPtr)
fmt.Println("numb:", *numbPtr)
fmt.Println("fork:", *forkPtr)
fmt.Println("svar:", svar)
fmt.Println("tail:", flag.Args())
}
package main
import (
"flag"
"fmt"
"os"
)
func main() {
fooCmd := flag.NewFlagSet("foo", flag.ExitOnError)
fooEnable := fooCmd.Bool("enable", false, "enable")
fooName := fooCmd.String("name", "", "name")
barCmd := flag.NewFlagSet("bar", flag.ExitOnError)
barLevel := barCmd.Int("level", 0, "level")
if len(os.Args) < 2 {
fmt.Println("expected 'foo' or 'bar' subcommands")
os.Exit(1)
}
switch os.Args[1] {
case "foo":
fooCmd.Parse(os.Args[2:])
fmt.Println("subcommand 'foo'")
fmt.Println(" enable:", *fooEnable)
fmt.Println(" name:", *fooName)
fmt.Println(" tail:", fooCmd.Args())
case "bar":
barCmd.Parse(os.Args[2:])
fmt.Println("subcommand 'bar'")
fmt.Println(" level:", *barLevel)
fmt.Println(" tail:", barCmd.Args())
default:
fmt.Println("expected 'foo' or 'bar' subcommands")
os.Exit(1)
}
}
package main
import (
"fmt"
"math"
)
const s string = "constant"
//常量不允许修改
func main() {
fmt.Println(s)
const n = 500000000 //5*10^8
const d = 3e20 / n //3*10^20
fmt.Println(d) //0.6*10^12 = 6 * 10^11
fmt.Println(int64(d))
//math.sin需要float64 n会自动确认类型
fmt.Println(math.Sin(n))
}
package main
import (
"fmt"
"net/http"
"time"
)
func hello1(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
fmt.Println("server: hello handler started")
defer fmt.Println("server: hello handler ended")
select {
case <-time.After(10 * time.Second):
fmt.Fprintf(w, "hello\n")
case <-ctx.Done():
err := ctx.Err()
fmt.Println("server:", err)
internalError := http.StatusInternalServerError
http.Error(w, err.Error(), internalError)
}
}
func main() {
http.HandleFunc("/hello", hello)
http.ListenAndServe(":8090", nil)
}
package main
import (
"fmt"
"os"
)
func main() {
f := createFile("/tmp/defer.txt")
defer closeFile(f)
writeFile(f)
}
func createFile(p string) *os.File {
fmt.Println("creating")
f, err := os.Create(p)
if err != nil {
panic(err)
}
return f
}
func writeFile(f *os.File) {
fmt.Println("writing")
fmt.Fprintln(f, "data")
}
func closeFile(f *os.File) {
fmt.Println("closing")
err := f.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
package main
import (
"fmt"
"os"
"path/filepath"
)
func check2(e error) {
if e != nil {
panic(e)
}
}
func main() {
err := os.Mkdir("subdir", 0755)
check2(err)
defer os.RemoveAll("subdir")
createEmptyFile := func(name string) {
d := []byte("")
check2(os.WriteFile(name, d, 0644))
}
createEmptyFile("subdir/file1")
err = os.MkdirAll("subdir/parent/child", 0755)
check2(err)
createEmptyFile("subdir/parent/file2")
createEmptyFile("subdir/parent/file3")
createEmptyFile("subdir/parent/child/file4")
c, err := os.ReadDir("subdir/parent")
check2(err)
fmt.Println("Listing subdir/parent")
for _, entry := range c {
fmt.Println(" ", entry.Name(), entry.IsDir())
}
err = os.Chdir("subdir/parent/child")
check2(err)
c, err = os.ReadDir(".")
check2(err)
fmt.Println("Listing subdir/parent/child")
for _, entry := range c {
fmt.Println(" ", entry.Name(), entry.IsDir())
}
err = os.Chdir("../../..")
check2(err)
fmt.Println("Visiting subdir")
err = filepath.Walk("subdir", visit)
}
func visit(p string, info os.FileInfo, err error) error {
if err != nil {
return err
}
fmt.Println(" ", p, info.IsDir())
return nil
}
E-H
package main
import "fmt"
//创建base结构体
type base struct {
age int
num int
}
//(参数列表):b base (返回值类型)describe() string
func (b base) describe() string {
return fmt.Sprintf("base with num=%v", b.num)
}
//创建container结构体,包含base?
type container struct {
base
str string
}
func main() {
//co 是container的一个对象
co := container{
//必须对base进行显示初始化
base: base{
num: 1,
},
str: "some name",
}
fmt.Printf("co={num: %v, str: %v}\n", co.num, co.str)
fmt.Println("also num:", co.base.num)
//co(container)->base str->base.describe
//两种访问方法均可
//fmt.Println("describe:", co.base.describe()) --1
fmt.Println("describe:", co.describe()) //--2
//创建一个describer接口 访问describe方法
type describer interface {
describe() string
}
var d describer = co
fmt.Println("describer:", d.describe())
}
// Circle ----------------------------
//比如说,在2D绘图程序当中,我们可能会定义以下两个结构类型
//圆圈
/*
type Circle struct {
X, Y, Radius int
}
//Wheel 车轮
type Wheel struct {
X, Y, Radius, Spokes int
}
func main() {
var w Wheel
w.X = 8
w.Y = 8
w.Radius = 5
w.Spokes = 20
}
*/
//--------------------------------------
//但是当支持的形状变多了之后 我们需要重构相同的部分
//--------------------------------------
/*
type Point struct {
X,Y int
}
type Circle struct {
Center Point
Radius int
}
type Wheel struct {
Circle Circle
Spokes int
}
func main() {
var w Wheel
w.Circle.Center.X = 8
w.Circle.Center.Y = 8
w.Circle.Radius = 5
w.Spokes = 20
}
*/
//程序结构简单了,但是访问wheel成员变得麻烦了
//----------------------------
//结构体嵌套和匿名成员的引入
//匿名成员:Go允许我们定义不带名称的结构体成员,只需要指定类型即可;
//这种结构体成员称作匿名成员。这个结构体成员的类型必须是一个命名类型
//或者指向命名类型的指针
/*
type Point struct {
X,Y int
}
type Circle struct {
Point
Radius int
}
type Wheel struct {
Circle
Spokes int
}
func main() {
var w Wheel
w.X = 8
w.Y = 8
w.Radius = 5
w.Spokes = 20
}
*/
package main
import (
"fmt"
"os"
"strings"
)
func main() {
os.Setenv("FOO", "1")
fmt.Println("FOO:", os.Getenv("FOO"))
fmt.Println("BAR:", os.Getenv("BAR"))
fmt.Println()
for _, e := range os.Environ() {
pair := strings.SplitN(e, "=", 2)
fmt.Println(pair[0])
}
}
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
secs := now.Unix()
nanos := now.UnixNano()
fmt.Println(now)
millis := nanos / 1000000
fmt.Println(secs)
fmt.Println(millis)
fmt.Println(nanos)
fmt.Println(time.Unix(secs, 0))
fmt.Println(time.Unix(0, nanos))
}
package main
import (
"errors"
"fmt"
)
//参数arg 返回int error两个参数
func f1(arg int) (int, error) {
//若arg==42
if arg == 42 {
//返回int=-1 error 错误信息 can't work with 42
return -1, errors.New("can't work with 42")
}
//若不是则返回arg+3 , nil
return arg + 3, nil
}
//定义argError结构体
type argError struct {
arg int
prob string
}
func (e *argError) Error() string {
return fmt.Sprintf("%d - %s", e.arg, e.prob)
}
func f2(arg int) (int, error) {
if arg == 42 {
return -1, &argError{arg, "can't work with it"}
}
return arg + 3, nil
}
func main() {
//遍历{7,42}这个切片,空白化(索引值index)(key)值为_,value值为i。
for _, i := range []int{7, 42} {
//第一遍
//i=7, r,e传入f1中的int error两个参数,当e 不为nil时
//转到f1判断,因为i->arg=7 != 42 ->return arg+3,nil ->r=10,e=nil
//不满足if条件 走else分支
//第二遍
//i=42,其他同上,向f1方法传入i=42的值->return -1,errors.New(can't work with 42)
//满足if条件。打印f1 failed:can't work with 42------------------②
if r, e := f1(i); e != nil {
fmt.Println("f1 failed:", e)
} else {
fmt.Println("f1 worked:", r) //打印 f1 worked: 10 ------①
}
}
//第一遍同上
//第二遍 return -1, &argError{arg, "can't work with it"}
for _, i := range []int{7, 42} {
if r, e := f2(i); e != nil {
fmt.Println("f2 failed:", e) //打印 f2 failed: 42 - can't work with it----④
} else {
fmt.Println("f2 worked:", r) //打印 f2 worked: 10 ------③
}
}
//e接收f2返回的信息 &argError{arg, "can't work with it"}
_, e := f2(42)
//ar ok 分别接收e的arg 和 字符串;当ok也就是字符串不为空时
if ae, ok := e.(*argError); ok {
//打印两条语句
fmt.Println(ae.arg)
fmt.Println(ae.prob)
}
}
package main
import (
"os"
"os/exec"
"syscall"
)
func main() {
binary, lookErr := exec.LookPath("ls")
if lookErr != nil {
panic(lookErr)
}
args := []string{"ls", "-a", "-l", "-h"}
env := os.Environ()
//execErr := syscall.Exec(binary, args, env)
if execErr != nil {
panic(execErr)
}
}
package main
import (
"fmt"
"os"
"strings"
)
func main() {
// ! 不会被打印出来
defer fmt.Println("!")
os.Exit(3)
}
func twoSum(nums []int, target int) []int {
//1.暴力解法
// for i:=0;i<len(nums);i++{
// for j := 0;j<len(nums);j++{
// if nums[i]+nums[j] == target && i!= j{
// return []int{i,j}
// }
// }
// }
// return nil
//2.哈希表
m := map[int]int{}
for i := 0; i < len(nums); i++ {
other := target - nums[i]
if p, ok := m[other]; ok {
return []int{p, i}
}
m[nums[i]] = i
}
return nil
}
func isPalindrome(s string) bool {
q, p := 0, len(s)-1
s = strings.ToUpper(s)
for q <= p {
//确保左右两边都是有效字符
if !ischar(s[q]) {
q++
} else if !ischar(s[p]) {
p--
} else if s[q] != s[p] {
return false
}
//是字符,正常左右两边走
q++
p--
}
return true
}
func ischar(ch byte) bool {
return (ch <= 'Z' && ch >= 'A') || (ch >= '0' && ch <= '9')
}
package main
import (
"fmt"
"path/filepath"
"strings"
)
func main() {
p := filepath.Join("dir1", "dir2", "filename")
fmt.Println("p:", p)
fmt.Println(filepath.Join("dir1//", "filename"))
fmt.Println(filepath.Join("dir1/../dir1", "filename"))
fmt.Println("Dir(p):", filepath.Dir(p))
fmt.Println("Base(p):", filepath.Base(p))
fmt.Println(filepath.IsAbs("dir/file"))
fmt.Println(filepath.IsAbs("/dir/file"))
filename := "config.json"
ext := filepath.Ext(filename)
fmt.Println(ext)
fmt.Println(strings.TrimSuffix(filename, ext))
rel, err := filepath.Rel("a/b", "a/b/t/file")
if err != nil {
panic(err)
}
fmt.Println(rel)
rel, err = filepath.Rel("a/b", "a/c/t/file")
if err != nil {
panic(err)
}
fmt.Println(rel)
}
package main
import "fmt"
func main() {
//1-3
i := 1
for i <= 3 {
fmt.Println(i)
i = i + 1
}
//7-9
for j := 7; j <= 9; j++ {
fmt.Println(j)
}
//loop 相当于 while(true){break}
for {
fmt.Println("loop")
break
}
//打印奇数(0-5之间)
for n := 0; n <= 5; n++ {
if n%2 == 0 {
continue
}
fmt.Println(n)
}
}
package main
import "fmt"
func plus(a int, b int) int {
return a + b
}
func plusPlus(a, b, c int) int {
return a + b + c
}
func main() {
res := plus(1, 2)
fmt.Println("1+2 =", res)
res = plusPlus(1, 2, 3)
fmt.Println("1+2+3 =", res)
}
package main
import "fmt"
// MapKeys 泛型:类型参数
// -----------------------------------------------------------------
// type comparable interface{ comparable }
// comparable是一个由所有可比较类型实现的接口
// (布尔值、数字、字符串、指针、通道、可比类型数组、结构的字段都是可比较的类型)。
// 可比接口只能作为类型参数约束使用,不是变量的类型。
// -----------------------------------------------------------------
// type any = interface{}
// any是接口{}的别名,在所有方面都等价于接口{}。
func MapKeys[K comparable, V any](m map[K]V) []K {
//属实没看懂...
r := make([]K, 0, len(m))
for k := range m {
r = append(r, k)
}
return r
}
type List[T any] struct {
head, tail *element[T]
}
type element[T any] struct {
next *element[T]
val T
}
func (lst *List[T]) Push(v T) {
if lst.tail == nil {
lst.head = &element[T]{val: v}
lst.tail = lst.head
} else {
lst.tail.next = &element[T]{val: v}
lst.tail = lst.tail.next
}
}
func (lst *List[T]) GetAll() []T {
var elems []T
for e := lst.head; e != nil; e = e.next {
elems = append(elems, e.val)
}
return elems
}
func main() {
//创建一个map key(int)-value(string) 并赋初值
var m = map[int]string{1: "2", 2: "4", 4: "8"}
//打印keys值 1 2 4
fmt.Println("keys m:", MapKeys(m))
_ = MapKeys[int, string](m)
lst := List[int]{}
lst.Push(10)
lst.Push(13)
lst.Push(23)
fmt.Println("list:", lst.GetAll())
}
package main
import (
"fmt"
"time"
)
func f(from string) {
for i := 0; i < 10; i++ {
//解锁fmt.Println用法
//func Println(a ...any) (n int, err error) {
// return Fprintln(os.Stdout, a...)
//}
fmt.Println(from, ":", i)
}
}
func main() {
//并发执行direct 和 goroutine
//异步进行
f("direct")
//go f(s) 在一个协程中调用这个函数。 这个新的 Go 协程将会 并发地 执行这个函数。
go f("goroutine")
//going的位置会不确定
go func(msg string) {
fmt.Println(msg)
}("going")
time.Sleep(time.Second)
fmt.Println("done")
}
package main
import (
"bufio"
"fmt"
"net/http"
)
func main() {
resp, err := http.Get("http://gobyexample.com")
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("Response status:", resp.Status)
scanner := bufio.NewScanner(resp.Body)
for i := 0; scanner.Scan() && i < 5; i++ {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
panic(err)
}
}
package main
import (
"fmt"
"net/http"
)
func hello(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "hello\n")
}
func headers(w http.ResponseWriter, req *http.Request) {
for name, headers := range req.Header {
for _, h := range headers {
fmt.Fprintf(w, "%v: %v\n", name, h)
}
}
}
func main() {
http.HandleFunc("/hello", hello)
http.HandleFunc("/headers", headers)
http.ListenAndServe(":8090", nil)
}
I-L
package main
import "fmt"
func main() {
//判断奇偶
if 7%2 == 0 {
fmt.Println("7 is even") //偶数
} else {
fmt.Println("7 is odd") //奇数
}
//能否整除
if 8%4 == 0 {
fmt.Println("8 is divisible by 4")
}
//判断数是一位数还是多位数(0-∞),其余输出负数
//注: C/C++ Java 都有的三元运算符,在Go中并没有
//圆括号可以省略不写(推荐不写) {}是必需的
if num := 9; num < 0 {
fmt.Println(num, "is negative")
} else if num < 10 {
fmt.Println(num, "has 1 digit")
} else {
fmt.Println(num, "has multiple digits")
}
}
package main
import (
"fmt"
"math"
)
//接口对area perim 两种方法进行了再次抽象
type geometry interface {
area() float64
perim() float64
}
type rect struct {
width, height float64
}
type circle struct {
radius float64
}
func (r rect) area() float64 {
return r.width * r.height
}
func (r rect) perim() float64 {
return 2*r.width + 2*r.height
}
func (c circle) area() float64 {
return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
return 2 * math.Pi * c.radius
}
//geometry:几何体
func measure(g geometry) {
//输出自身: {3 4}、 {5}
fmt.Println(g)
//输出面积/周长
fmt.Println(g.area())
fmt.Println(g.perim())
}
func main() {
//创建r(rest)结构体 宽3高4
r := rect{width: 3, height: 4}
//创建⚪(circle) 半径5
c := circle{radius: 5}
measure(r)
measure(c)
}
package main
import (
"encoding/json"
"fmt"
"os"
)
type response1 struct {
Page int
Fruits []string
}
type response2 struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
}
func main() {
bolB, _ := json.Marshal(true)
fmt.Println(string(bolB))
intB, _ := json.Marshal(1)
fmt.Println(string(intB))
fltB, _ := json.Marshal(2.34)
fmt.Println(string(fltB))
strB, _ := json.Marshal("gopher")
fmt.Println(string(strB))
slcD := []string{"apple", "peach", "pear"}
slcB, _ := json.Marshal(slcD)
fmt.Println(string(slcB))
mapD := map[string]int{"apple": 5, "lettuce": 7}
mapB, _ := json.Marshal(mapD)
fmt.Println(string(mapB))
res1D := &response1{
Page: 1,
Fruits: []string{"apple", "peach", "pear"}}
res1B, _ := json.Marshal(res1D)
fmt.Println(string(res1B))
res2D := &response2{
Page: 1,
Fruits: []string{"apple", "peach", "pear"}}
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B))
byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
var dat map[string]interface{}
if err := json.Unmarshal(byt, &dat); err != nil {
panic(err)
}
fmt.Println(dat)
num := dat["num"].(float64)
fmt.Println(num)
strs := dat["strs"].([]interface{})
str1 := strs[0].(string)
fmt.Println(str1)
str := `{"page": 1, "fruits": ["apple", "peach"]}`
res := response2{}
json.Unmarshal([]byte(str), &res)
fmt.Println(res)
fmt.Println(res.Fruits[0])
enc := json.NewEncoder(os.Stdout)
d := map[string]int{"apple": 5, "lettuce": 7}
enc.Encode(d)
}
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
ucl := strings.ToUpper(scanner.Text())
fmt.Println(ucl)
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
M-P
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
package main
import "fmt"
func main() {
m := make(map[string]int)
//建立map key-value类型 key:string value:int
m["k1"] = 7
m["k2"] = 13
fmt.Println("map:", m)
v1 := m["k1"]
fmt.Println("v1: ", v1)
fmt.Println("len:", len(m)) //2
//删除key 为 k2的键
delete(m, "k2")
fmt.Println("map:", m)
//面对不需要的值用 _ 空白标识符
_, prs := m["k2"]
fmt.Println("prs:", prs) //false
n := map[string]int{"foo": 1, "bar": 2}
fmt.Println("map:", n)
}
package main
import "fmt"
type rect1 struct {
width, height int
}
//method1
func (r *rect1) area() int {
return r.width * r.height
}
//method2
func (r rect1) perim() int {
return 2*r.width + 2*r.height
}
func main() {
//rect是矩形
//创建结构体r(rect)并赋默认值
r := rect{width: 10, height: 5}
//使用m1计算面积
fmt.Println("area: ", r.area())
//使用m1计算周长
fmt.Println("perim:", r.perim())
//通过使用指针来避免拷贝(浪费空间)
rp := &r
fmt.Println("area: ", rp.area())
fmt.Println("perim:", rp.perim())
}
package main
import "fmt"
func vals() (int, int) {
return 3, 7
}
func main() {
//支持多返回值
a, b := vals()
fmt.Println(a)
fmt.Println(b)
_, c := vals()
fmt.Println(c)
}
package main
import (
"fmt"
"sync"
)
type Container struct {
mu sync.Mutex
counters map[string]int
}
func (c *Container) inc(name string) {
c.mu.Lock()
defer c.mu.Unlock()
c.counters[name]++
}
func main() {
c := Container{
counters: map[string]int{"a": 0, "b": 0},
}
var wg sync.WaitGroup
doIncrement := func(name string, n int) {
for i := 0; i < n; i++ {
c.inc(name)
}
wg.Done()
}
wg.Add(3)
go doIncrement("a", 10000)
go doIncrement("a", 10000)
go doIncrement("b", 10000)
wg.Wait()
fmt.Println(c.counters)
}
package main
import "fmt"
func main() {
messages := make(chan string)
signals := make(chan bool)
select {
case msg := <-messages:
fmt.Println("received message", msg)
default:
fmt.Println("no message received")
}
msg := "hi"
select {
case messages <- msg:
fmt.Println("sent message", msg)
default:
fmt.Println("no message sent")
}
select {
case msg := <-messages:
fmt.Println("received message", msg)
case sig := <-signals:
fmt.Println("received signal", sig)
default:
fmt.Println("no activity")
}
}
package main
import (
"fmt"
"strconv"
)
func main() {
f, _ := strconv.ParseFloat("1.234", 64)
fmt.Println(f)
i, _ := strconv.ParseInt("123", 0, 64)
fmt.Println(i)
d, _ := strconv.ParseInt("0x1c8", 0, 64)
fmt.Println(d)
u, _ := strconv.ParseUint("789", 0, 64)
fmt.Println(u)
k, _ := strconv.Atoi("135")
fmt.Println(k)
_, e := strconv.Atoi("wat")
fmt.Println(e)
}
package main
import "os"
func main() {
panic("a problem")
_, err := os.Create("/tmp/file")
if err != nil {
panic(err)
}
}
package main
import "fmt"
//值传递
func zeroval(ival int) {
ival = 0
}
//“引用”传递 ->本质还是值传递,只不过值变成了指针所指的逻辑地址
func zeroptr(iptr *int) {
*iptr = 0
}
func main() {
i := 1
fmt.Println("initial:", i)
zeroval(i)
fmt.Println("zeroval:", i)
zeroptr(&i)
fmt.Println("zeroptr:", i)
//打印i所在的逻辑地址(每个人机器打出来的值都会有所不同,由OS分配)
//fmt.Println(&i) 0xc000016098
fmt.Println("pointer:", &i)
}
R-S
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
//生成随机数0-100
fmt.Print(rand.Intn(100), ",")
fmt.Print(rand.Intn(100))
fmt.Println()
//生成随机float64位浮点数(0.0-1.0)
fmt.Println(rand.Float64())
//5.0-10.0
fmt.Print((rand.Float64()*5)+5, ",")
fmt.Print((rand.Float64() * 5) + 5)
fmt.Println()
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
fmt.Print(r1.Intn(100), ",")
fmt.Print(r1.Intn(100))
fmt.Println()
//使用相同种子生成的随机数生成器,会生成相同的随机数序列
s2 := rand.NewSource(42)
r2 := rand.New(s2)
//此处①
fmt.Print(r2.Intn(100), ",")
fmt.Print(r2.Intn(100))
fmt.Println()
s3 := rand.NewSource(42)
r3 := rand.New(s3)
//此处②同①生成相同的两个随机数
fmt.Print(r3.Intn(100), ",")
fmt.Print(r3.Intn(100))
}
package main
import "fmt"
func main() {
//创建切片nums len = 3
nums := []int{2, 3, 4}
sum := 0
//对nums中的数据求和,存放在num中
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)
//取出num ==3时,对应的索引值
for i, num := range nums {
if num == 3 {
fmt.Println("index:", i)
}
}
//创建key-value的map
kvs := map[string]string{"a": "apple", "b": "banana", "p": "peach"}
//随机取值 map无序
for k, v := range kvs {
fmt.Printf("%s -> %s\n", k, v)
}
for k := range kvs {
fmt.Println("key:", k)
}
for i, c := range "go" {
//字符串 输出索引值 0 1 和其对应的ascii码值
fmt.Println(i, c)
//Output:
//0 103
//1 111
}
}
package main
import "fmt"
func main() {
queue := make(chan string, 2)
queue <- "one"
queue <- "two"
close(queue)
for elem := range queue {
fmt.Println(elem)
}
}
package main
import (
"fmt"
"time"
)
func main() {
requests := make(chan int, 5)
for i := 1; i <= 5; i++ {
requests <- i
}
close(requests)
limiter := time.Tick(200 * time.Millisecond)
for req := range requests {
<-limiter
fmt.Println("request", req, time.Now())
}
burstyLimiter := make(chan time.Time, 3)
for i := 0; i < 3; i++ {
burstyLimiter <- time.Now()
}
go func() {
for t := range time.Tick(200 * time.Millisecond) {
burstyLimiter <- t
}
}()
burstyRequests := make(chan int, 5)
for i := 1; i <= 5; i++ {
burstyRequests <- i
}
close(burstyRequests)
for req := range burstyRequests {
<-burstyLimiter
fmt.Println("request", req, time.Now())
}
}
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
dat, err := os.ReadFile("/tmp/dat")
check(err)
fmt.Print(string(dat))
f, err := os.Open("/tmp/dat")
check(err)
b1 := make([]byte, 5)
n1, err := f.Read(b1)
check(err)
fmt.Printf("%d bytes: %s\n", n1, string(b1[:n1]))
o2, err := f.Seek(6, 0)
check(err)
b2 := make([]byte, 2)
n2, err := f.Read(b2)
check(err)
fmt.Printf("%d bytes @ %d: ", n2, o2)
fmt.Printf("%v\n", string(b2[:n2]))
o3, err := f.Seek(6, 0)
check(err)
b3 := make([]byte, 2)
n3, err := io.ReadAtLeast(f, b3, 2)
check(err)
fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3))
_, err = f.Seek(0, 0)
check(err)
r4 := bufio.NewReader(f)
b4, err := r4.Peek(5)
check(err)
fmt.Printf("5 bytes: %s\n", string(b4))
f.Close()
}
package main
import "fmt"
func mayPanic() {
panic("a problem")
}
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered. Error:\n", r)
}
}()
mayPanic()
fmt.Println("After mayPanic()")
}
package main
import "fmt"
func fact(n int) int {
if n == 0 {
return 1
}
return n * fact(n-1)
}
func main() {
//计算7的阶乘
fmt.Println(fact(7))
//1 2 6 24 120 720 5040...
var fib func(n int) int
//计算斐波那契数列
fib = func(n int) int {
if n < 2 {
return n
}
return fib(n-1) + fib(n-2)
}
//1 1 2 3 5 8 13...
fmt.Println(fib(7))
}
package main
import (
"bytes"
"fmt"
"regexp"
)
func main() {
match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
fmt.Println(match)
r, _ := regexp.Compile("p([a-z]+)ch")
fmt.Println(r.MatchString("peach"))
fmt.Println(r.FindString("peach punch"))
fmt.Println("idx:", r.FindStringIndex("peach punch"))
fmt.Println(r.FindStringSubmatch("peach punch"))
fmt.Println(r.FindStringSubmatchIndex("peach punch"))
fmt.Println(r.FindAllString("peach punch pinch", -1))
fmt.Println("all:", r.FindAllStringSubmatchIndex(
"peach punch pinch", -1))
fmt.Println(r.FindAllString("peach punch pinch", 2))
fmt.Println(r.Match([]byte("peach")))
r = regexp.MustCompile("p([a-z]+)ch")
fmt.Println("regexp:", r)
fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))
in := []byte("a peach")
out := r.ReplaceAllFunc(in, bytes.ToUpper)
fmt.Println(string(out))
}
package main
import (
"fmt"
"time"
)
func main() {
c1 := make(chan string)
c2 := make(chan string)
go func() {
time.Sleep(1 * time.Second)
c1 <- "one"
}()
go func() {
time.Sleep(2 * time.Second)
c2 <- "two"
}()
for i := 0; i < 2; i++ {
select {
case msg1 := <-c1:
fmt.Println("received", msg1)
case msg2 := <-c2:
fmt.Println("received", msg2)
}
}
}
package main
import (
"crypto/sha256"
"fmt"
)
func main() {
s := "sha256 this string"
h := sha256.New()
h.Write([]byte(s))
bs := h.Sum(nil)
fmt.Println(s)
fmt.Printf("%x\n", bs)
}
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
)
func main() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
done := make(chan bool, 1)
go func() {
sig := <-sigs
fmt.Println()
fmt.Println(sig)
done <- true
}()
fmt.Println("awaiting signal")
<-done
fmt.Println("exiting")
}
package main
import "fmt"
func main() {
//创建切片,默认值为空字符串 ""
s := make([]string, 3)
fmt.Println("emp:", s)
//对s切片赋值a b c
s[0] = "a"
s[1] = "b"
s[2] = "c"
fmt.Println("set:", s)
fmt.Println("get:", s[2])
//获取长度
fmt.Println("len:", len(s))
//向s中追加 "d"
s = append(s, "d")
//slice 扩容可查看src/runtime/slice.go 下的 growslice 函数
s = append(s, "e", "f")
fmt.Println("apd:", s)
//创建与c同样大小的c slice
c := make([]string, len(s))
//切片复制
copy(c, s)
fmt.Println("cpy:", c)
//左取右不取
l := s[2:5]
fmt.Println("sl1:", l)
l = s[:5]
fmt.Println("sl2:", l)
l = s[2:]
fmt.Println("sl3:", l)
t := []string{"g", "h", "i"}
fmt.Println("dcl:", t)
//二维切片
twoD := make([][]int, 3)
for i := 0; i < 3; i++ {
innerLen := i + 1
twoD[i] = make([]int, innerLen)
for j := 0; j < innerLen; j++ {
twoD[i][j] = i + j
}
}
fmt.Println("2d: ", twoD)
//OutPut: [[0] [1 2] [2 3 4]]
}
package main
import (
"fmt"
"sort"
)
func main() {
strs := []string{"c", "a", "b"}
sort.Strings(strs)
fmt.Println("Strings:", strs)
ints := []int{7, 2, 4}
sort.Ints(ints)
fmt.Println("Ints: ", ints)
s := sort.IntsAreSorted(ints)
fmt.Println("Sorted: ", s)
}
package main
import (
"fmt"
"sort"
)
type byLength []string
func (s byLength) Len() int {
return len(s)
}
func (s byLength) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s byLength) Less(i, j int) bool {
return len(s[i]) < len(s[j])
}
func main() {
fruits := []string{"peach", "banana", "kiwi"}
sort.Sort(byLength(fruits))
fmt.Println(fruits)
}
package main
import (
"fmt"
"io"
"os/exec"
)
func main() {
dateCmd := exec.Command("date")
dateOut, err := dateCmd.Output()
if err != nil {
panic(err)
}
fmt.Println("> date")
fmt.Println(string(dateOut))
grepCmd := exec.Command("grep", "hello")
grepIn, _ := grepCmd.StdinPipe()
grepOut, _ := grepCmd.StdoutPipe()
grepCmd.Start()
grepIn.Write([]byte("hello grep\ngoodbye grep"))
grepIn.Close()
grepBytes, _ := io.ReadAll(grepOut)
grepCmd.Wait()
fmt.Println("> grep hello")
fmt.Println(string(grepBytes))
lsCmd := exec.Command("bash", "-c", "ls -a -l -h")
lsOut, err := lsCmd.Output()
if err != nil {
panic(err)
}
fmt.Println("> ls -a -l -h")
fmt.Println(string(lsOut))
}
package main
import (
"fmt"
"math/rand"
"sync/atomic"
"time"
)
type readOp struct {
key int
resp chan int
}
type writeOp struct {
key int
val int
resp chan bool
}
func main() {
var readOps uint64
var writeOps uint64
reads := make(chan readOp)
writes := make(chan writeOp)
go func() {
var state = make(map[int]int)
for {
select {
case read := <-reads:
read.resp <- state[read.key]
case write := <-writes:
state[write.key] = write.val
write.resp <- true
}
}
}()
for r := 0; r < 100; r++ {
go func() {
for {
read := readOp{
key: rand.Intn(5),
resp: make(chan int)}
reads <- read
<-read.resp
atomic.AddUint64(&readOps, 1)
time.Sleep(time.Millisecond)
}
}()
}
for w := 0; w < 10; w++ {
go func() {
for {
write := writeOp{
key: rand.Intn(5),
val: rand.Intn(100),
resp: make(chan bool)}
writes <- write
<-write.resp
atomic.AddUint64(&writeOps, 1)
time.Sleep(time.Millisecond)
}
}()
}
time.Sleep(time.Second)
readOpsFinal := atomic.LoadUint64(&readOps)
fmt.Println("readOps:", readOpsFinal)
writeOpsFinal := atomic.LoadUint64(&writeOps)
fmt.Println("writeOps:", writeOpsFinal)
}
package main
import (
"fmt"
"os"
)
type point struct {
x, y int
}
func main() {
p := point{1, 2}
fmt.Printf("struct1: %v\n", p)
fmt.Printf("struct2: %+v\n", p)
fmt.Printf("struct3: %#v\n", p)
fmt.Printf("type: %T\n", p)
fmt.Printf("bool: %t\n", true)
fmt.Printf("int: %d\n", 123)
fmt.Printf("bin: %b\n", 14)
fmt.Printf("char: %c\n", 33)
fmt.Printf("hex: %x\n", 456)
fmt.Printf("float1: %f\n", 78.9)
fmt.Printf("float2: %e\n", 123400000.0)
fmt.Printf("float3: %E\n", 123400000.0)
fmt.Printf("str1: %s\n", "\"string\"")
fmt.Printf("str2: %q\n", "\"string\"")
fmt.Printf("str3: %x\n", "hex this")
fmt.Printf("pointer: %p\n", &p)
fmt.Printf("width1: |%6d|%6d|\n", 12, 345)
fmt.Printf("width2: |%6.2f|%6.2f|\n", 1.2, 3.45)
fmt.Printf("width3: |%-6.2f|%-6.2f|\n", 1.2, 3.45)
fmt.Printf("width4: |%6s|%6s|\n", "foo", "b")
fmt.Printf("width5: |%-6s|%-6s|\n", "foo", "b")
s := fmt.Sprintf("sprintf: a %s", "string")
fmt.Println(s)
fmt.Fprintf(os.Stderr, "io: an %s\n", "error")
}
package main
import (
"fmt"
s "strings"
)
var p = fmt.Println
func main() {
p("Contains: ", s.Contains("test", "es"))
p("Count: ", s.Count("test", "t"))
p("HasPrefix: ", s.HasPrefix("test", "te"))
p("HasSuffix: ", s.HasSuffix("test", "st"))
p("Index: ", s.Index("test", "e"))
p("Join: ", s.Join([]string{"a", "b"}, "-"))
p("Repeat: ", s.Repeat("a", 5))
p("Replace: ", s.Replace("foo", "o", "0", -1))
p("Replace: ", s.Replace("foo", "o", "0", 1))
p("Split: ", s.Split("a-b-c-d-e", "-"))
p("ToLower: ", s.ToLower("TEST"))
p("ToUpper: ", s.ToUpper("test"))
p()
p("Len: ", len("hello"))
p("Char:", "hello"[1])
}
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
//电脑用光标移动,会数出六个字符 6*3 = 18
const s = "สวัสดี"
//打印的长长度是计算的byte值
fmt.Println("Len:", len(s))
//打印[]byte值 共18个
for i := 0; i < len(s); i++ {
fmt.Printf("%x ", s[i])
}
//e0 b8 aa e0 b8 a7 e0 b8 b1 e0 b8 aa e0 b8 94 e0 b8 b5
fmt.Println()
fmt.Println("Rune count:", utf8.RuneCountInString(s))
//分别打印UTF-8 code point值和其偏移量
for idx, runeValue := range s {
fmt.Printf("%#U starts at %d\n", runeValue, idx)
}
fmt.Println("\nUsing DecodeRuneInString")
for i, w := 0, 0; i < len(s); i += w {
runeValue, width := utf8.DecodeRuneInString(s[i:])
fmt.Printf("%#U starts at %d\n", runeValue, i)
w = width
examineRune(runeValue)
}
}
func examineRune(r rune) {
if r == 't' {
fmt.Println("found tee")
} else if r == 'ส' {
fmt.Println("found so sua")
}
}
package main
import "fmt"
//创建结构体 person 包含name age两个字段
type person struct {
name string
age int
}
func newPerson(name string) *person {
p := person{name: name}
p.age = 42
return &p
}
func main() {
fmt.Println(person{"Bob", 20})
fmt.Println(person{name: "Alice", age: 30})
fmt.Println(person{name: "Fred"})
fmt.Println(&person{name: "Ann", age: 40})
fmt.Println(newPerson("Jon"))
s := person{name: "Sean", age: 50}
fmt.Println(s.name)
//对结构体指针使用 . 指针会被自动解引用。
sp := &s
fmt.Println(sp.age)
//修改结构体对应的字段值
sp.age = 51
fmt.Println(sp.age)
}
package main
import (
"fmt"
"time"
)
func main() {
//switch不需要break,Go中会自动添加
i := 2
fmt.Print("write ", i, " as ")
switch i {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
fmt.Println("It's the weekend")
default:
fmt.Println("It's a weekday")
}
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("It's before noon")
default:
fmt.Println("It's after noon")
}
//类型开关type switch比较类型,而非value.以此判断参数的类型值
whatAmI := func(i interface{}) {
switch t := i.(type) {
case bool:
fmt.Println("I'm a bool")
case int:
fmt.Println("I'm an int")
default:
fmt.Printf("Don't know type %T\n", t)
}
}
whatAmI(true)
whatAmI(1)
whatAmI("hey")
}
T-X
package main
import (
"os"
"text/template"
)
func main() {
t1 := template.New("t1")
t1, err := t1.Parse("Value is {{.}}\n")
if err != nil {
panic(err)
}
t1 = template.Must(t1.Parse("Value: {{.}}\n"))
t1.Execute(os.Stdout, "some text")
t1.Execute(os.Stdout, 5)
t1.Execute(os.Stdout, []string{
"Go",
"Rust",
"C++",
"C#",
})
Create := func(name, t string) *template.Template {
return template.Must(template.New(name).Parse(t))
}
t2 := Create("t2", "Name: {{.Name}}\n")
t2.Execute(os.Stdout, struct {
Name string
}{"Jane Doe"})
t2.Execute(os.Stdout, map[string]string{
"Name": "Mickey Mouse",
})
t3 := Create("t3",
"{{if . -}} yes {{else -}} no {{end}}\n")
t3.Execute(os.Stdout, "not empty")
t3.Execute(os.Stdout, "")
t4 := Create("t4",
"Range: {{range .}}{{.}} {{end}}\n")
t4.Execute(os.Stdout,
[]string{
"Go",
"Rust",
"C++",
"C#",
})
}
package main
import (
"fmt"
"os"
"path/filepath"
)
func check3(e error) {
if e != nil {
panic(e)
}
}
func main() {
f, err := os.CreateTemp("", "sample")
check3(err)
fmt.Println("Temp file name:", f.Name())
defer os.Remove(f.Name())
_, err = f.Write([]byte{1, 2, 3, 4})
check3(err)
dname, err := os.MkdirTemp("", "sampledir")
fmt.Println("Temp dir name:", dname)
defer os.RemoveAll(dname)
fname := filepath.Join(dname, "file1")
err = os.WriteFile(fname, []byte{1, 2}, 0666)
check3(err)
}
package main
import (
"fmt"
"testing"
)
func IntMin(a, b int) int {
if a < b {
return a
}
return b
}
func TestIntMinBasic(t *testing.T) {
ans := IntMin(2, -2)
if ans != -2 {
t.Errorf("IntMin(2, -2) = %d; want -2", ans)
}
}
func TestIntMinTableDriven(t *testing.T) {
var tests = []struct {
a, b int
want int
}{
{0, 1, 0},
{1, 0, 0},
{2, -2, -2},
{0, -1, -1},
{-1, 0, -1},
}
for _, tt := range tests {
testname := fmt.Sprintf("%d,%d", tt.a, tt.b)
t.Run(testname, func(t *testing.T) {
ans := IntMin(tt.a, tt.b)
if ans != tt.want {
t.Errorf("got %d, want %d", ans, tt.want)
}
})
}
}
func BenchmarkIntMin(b *testing.B) {
for i := 0; i < b.N; i++ {
IntMin(1, 2)
}
}
package main
import (
"fmt"
"time"
)
func main() {
ticker := time.NewTicker(500 * time.Millisecond)
done := make(chan bool)
go func() {
for {
select {
case <-done:
return
case t := <-ticker.C:
fmt.Println("Tick at", t)
}
}
}()
time.Sleep(1600 * time.Millisecond)
ticker.Stop()
done <- true
fmt.Println("Ticker stopped")
}
package main
import (
"fmt"
"time"
)
func main() {
p := fmt.Println
now := time.Now()
p(now)
then := time.Date(
2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
p(then)
p(then.Year())
p(then.Month())
p(then.Day())
p(then.Hour())
p(then.Minute())
p(then.Second())
p(then.Nanosecond())
p(then.Location())
p(then.Weekday())
p(then.Before(now))
p(then.After(now))
p(then.Equal(now))
diff := now.Sub(then)
p(diff)
p(diff.Hours())
p(diff.Minutes())
p(diff.Seconds())
p(diff.Nanoseconds())
p(then.Add(diff))
p(then.Add(-diff))
}
package main
import (
"fmt"
"time"
)
func main() {
p := fmt.Println
t := time.Now()
p(t.Format(time.RFC3339))
t1, e := time.Parse(
time.RFC3339,
"2012-11-01T22:08:41+00:00")
p(t1)
p(t.Format("3:04PM"))
p(t.Format("Mon Jan _2 15:04:05 2006"))
p(t.Format("2006-01-02T15:04:05.999999-07:00"))
form := "3 04 PM"
t2, e := time.Parse(form, "8 41 PM")
p(t2)
fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second())
ansic := "Mon Jan _2 15:04:05 2006"
_, e = time.Parse(ansic, "8:41PM")
p(e)
}
package main
import (
"fmt"
"time"
)
func main() {
c1 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c1 <- "result 1"
}()
select {
case res := <-c1:
fmt.Println(res)
case <-time.After(1 * time.Second):
fmt.Println("timeout 1")
}
c2 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c2 <- "result 2"
}()
select {
case res := <-c2:
fmt.Println(res)
case <-time.After(3 * time.Second):
fmt.Println("timeout 2")
}
}
package main
import (
"fmt"
"time"
)
func main() {
timer1 := time.NewTimer(2 * time.Second)
<-timer1.C
fmt.Println("Timer 1 fired")
timer2 := time.NewTimer(time.Second)
go func() {
<-timer2.C
fmt.Println("Timer 2 fired")
}()
stop2 := timer2.Stop()
if stop2 {
fmt.Println("Timer 2 stopped")
}
time.Sleep(2 * time.Second)
}
package main
import (
"fmt"
"net"
"net/url"
)
func main() {
s := "postgres://user:pass@host.com:5432/path?k=v#f"
u, err := url.Parse(s)
if err != nil {
panic(err)
}
fmt.Println(u.Scheme)
fmt.Println(u.User)
fmt.Println(u.User.Username())
p, _ := u.User.Password()
fmt.Println(p)
fmt.Println(u.Host)
host, port, _ := net.SplitHostPort(u.Host)
fmt.Println(host)
fmt.Println(port)
fmt.Println(u.Path)
fmt.Println(u.Fragment)
fmt.Println(u.RawQuery)
m, _ := url.ParseQuery(u.RawQuery)
fmt.Println(m)
fmt.Println(m["k"][0])
}
package main
import "fmt"
func main() {
fmt.Println("go" + "lang")
fmt.Println("1+1 =", 1+1)
fmt.Println("7.0/3.0 =", 7.0/3.0)
//运用逻辑运算符
fmt.Println(true && false)
fmt.Println(true || false)
fmt.Println(!true)
}
package main
import "fmt"
func main() {
var a = "initial"
fmt.Println(a)
var b, c int = 1, 2
fmt.Println(b, c)
var d = true
fmt.Println(d)
var e int
fmt.Println(e)
//短变量声明 :=
f := "short"
fmt.Println(f)
}
package main
import "fmt"
//通过使用 ... 使函数接收任意数量的int作为参数
func sum(nums ...int) {
fmt.Print(nums, " ")
total := 0
for _, num := range nums {
total += num
}
fmt.Println(total)
}
func main() {
sum(1, 2)
sum(1, 2, 3)
nums := []int{1, 2, 3, 4}
sum(nums...)
}
package main
import (
"fmt"
"sync"
"time"
)
func worker2(id int) {
fmt.Printf("Worker %d starting\n", id)
time.Sleep(time.Second)
fmt.Printf("Worker %d done\n", id)
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
i := i
go func() {
defer wg.Done()
worker2(i)
}()
}
wg.Wait()
}
package main
import (
"fmt"
"time"
)
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Println("worker", id, "started job", j)
time.Sleep(time.Second)
fmt.Println("worker", id, "finished job", j)
results <- j * 2
}
}
func main() {
const numJobs = 5
jobs := make(chan int, numJobs)
results := make(chan int, numJobs)
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
for j := 1; j <= numJobs; j++ {
jobs <- j
}
close(jobs)
for a := 1; a <= numJobs; a++ {
<-results
}
}
package main
import (
"bufio"
"fmt"
"os"
)
func check1(e error) {
if e != nil {
panic(e)
}
}
func main() {
d1 := []byte("hello\ngo\n")
err := os.WriteFile("/tmp/dat1", d1, 0644)
check1(err)
f, err := os.Create("/tmp/dat2")
check1(err)
defer f.Close()
d2 := []byte{115, 111, 109, 101, 10}
n2, err := f.Write(d2)
check1(err)
fmt.Printf("wrote %d bytes\n", n2)
n3, err := f.WriteString("writes\n")
check1(err)
fmt.Printf("wrote %d bytes\n", n3)
f.Sync()
w := bufio.NewWriter(f)
n4, err := w.WriteString("buffered\n")
check1(err)
fmt.Printf("wrote %d bytes\n", n4)
w.Flush()
}
package main
import (
"encoding/xml"
"fmt"
)
type Plant struct {
XMLName xml.Name `xml:"plant"`
Id int `xml:"id,attr"`
Name string `xml:"name"`
Origin []string `xml:"origin"`
}
func (p Plant) String() string {
return fmt.Sprintf("Plant id=%v, name=%v, origin=%v",
p.Id, p.Name, p.Origin)
}
func main() {
coffee := &Plant{Id: 27, Name: "Coffee"}
coffee.Origin = []string{"Ethiopia", "Brazil"}
out, _ := xml.MarshalIndent(coffee, " ", " ")
fmt.Println(string(out))
fmt.Println(xml.Header + string(out))
var p Plant
if err := xml.Unmarshal(out, &p); err != nil {
panic(err)
}
fmt.Println(p)
tomato := &Plant{Id: 81, Name: "Tomato"}
tomato.Origin = []string{"Mexico", "California"}
type Nesting struct {
XMLName xml.Name `xml:"nesting"`
Plants []*Plant `xml:"parent>child>plant"`
}
nesting := &Nesting{}
nesting.Plants = []*Plant{coffee, tomato}
out, _ = xml.MarshalIndent(nesting, " ", " ")
fmt.Println(string(out))
}