Golang没有直接支持泛型,但可以使用空接口 interface{}
来实现类似的效果。
goCopy codefunc printType(value interface{}) {
fmt.Printf("Type: %T, Value: %v\n", value, value)
}
func main() {
printType(42)
printType("Hello, Golang!")
}
defer
用于延迟执行一个函数调用,通常用于资源释放或清理操作。
goCopy codefunc example() {
defer fmt.Println("Deferred statement")
fmt.Println("Normal statement")
}
range
迭代range
关键字用于迭代切片、数组、映射等数据结构。
goCopy codenumbers := []int{1, 2, 3, 4, 5}
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
闭包是一个包含了函数体和其所引用的变量的函数值。
goCopy codefunc adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
func main() {
add := adder()
fmt.Println(add(1)) // 输出: 1
fmt.Println(add(2)) // 输出: 3
}
通过sync.Map
可以实现并发安全的映射,避免在多个goroutine中出现竞态条件。
goCopy codevar m sync.Map
func main() {
m.Store("key", "value")
value, ok := m.Load("key")
fmt.Println(value, ok) // 输出: value true
}
context
进行超时和取消context
包提供了在goroutine之间传递取消信号和截止时间的机制。
goCopy codefunc process(ctx context.Context) {
select {
case <-time.After(2 * time.Second):
fmt.Println("Process completed")
case <-ctx.Done():
fmt.Println("Process canceled")
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
go process(ctx)
time.Sleep(3 * time.Second)
}
反射允许在运行时检查变量的类型和值,可以用于实现通用程序。
goCopy codefunc inspectValue(value interface{}) {
v := reflect.ValueOf(value)
t := reflect.TypeOf(value)
fmt.Printf("Type: %v, Value: %v\n", t, v)
}
func main() {
inspectValue(42)
inspectValue("Hello, Golang!")
}
http
包创建简单的Web服务器goCopy codepackage main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, Golang Web Server!")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
这些基础知识点涵盖了Golang中一些更深入的概念,包括泛型编程、defer、range迭代、闭包、并发安全Map、context、反射以及简单的Web服务器。深入理解这些概念可以帮助你更好地应用Golang进行更复杂和高级的编程任务。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。