go基础知识梳理

2023/09/28 go

go基础知识梳理

1、go语言参数传递到底是传值还是传引用?

https://blog.csdn.net/qq_39397165/article/details/109561839

2、make 和 new 的区别

.相同点:make 和 new 为指定的类型做内存分配 .不同点: make 只能为 slice map slice 做内存分配,并初始化底层的数据结构,返回的是类型的本身 new 支持所有传入的类型做内存分配,并返回指向该内存空间的指针

https://draveness.me/golang/docs/part2-foundation/ch05-keyword/golang-make-and-new/

3、defer

执行顺序先进后出

https://draveness.me/golang/docs/part2-foundation/ch05-keyword/golang-defer/

4、context

context并不能让真正让处理业务的协程退出

https://draveness.me/golang/docs/part3-runtime/ch06-concurrency/golang-context/

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"time"
)

func say(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithTimeout(r.Context(), 1*time.Second)
	defer cancel()
	var done = make(chan struct{}, 1)

	go handle(ctx, done)
	select {
	case <-ctx.Done():
		fmt.Println("Context canceled")
		w.Write([]byte("Context canceled"))
		return
	case <-done:
		fmt.Println("done !")
	}

	status, err := w.Write([]byte("hello world"))
	if err != nil {
		log.Print("write fail:%v", err)
	} else {
		log.Println("success: ", status)
	}

}

func handle(ctx context.Context, done chan<- struct{}) {

	for {

		select {
		case <-ctx.Done():
			log.Println("Handle canceled due to timeout or cancellation")
			return
		default:
			// 执行正常的处理逻辑
			time.Sleep(5 * time.Second)
			log.Println("Handle completed")
			done <- struct{}{}
			return
		}

	}

}

func main() {

	http.HandleFunc("/say", say)
	log.Fatal(http.ListenAndServe(":8090", nil))
}

Search

    Table of Contents