跳到主要内容

2 篇博文 含有标签「Golang」

查看所有标签

What is a channel in Go

· 阅读需 3 分钟
Ryan
Cloud-Native Operations Engineer

In Go, a channel is a powerful tool used to facilitate communication and synchronization between goroutines. Channels allow you to pass data between goroutines safely, without the need for explicit locking or other complex synchronization mechanisms.

How Channels Work?

Channels in Go provide a typed conduit through which goroutines can send and receive data.

You can think of a channel as a pipe: one goroutine sends data into the channel, and another goroutine receives the data from the other end.

Channels are typed, meaning that a channel can only transfer data of a specific type. For example, a channel of chan int can only pass integers.

0b36157df206

类型断言

· 阅读需 3 分钟
Ryan
Cloud-Native Operations Engineer

1. 类型断言的作用

在 Go 语言中,当一个结构体或其他类型赋值给 interface{} 时,Go 会将原始值和它的类型包装在接口中。此时使用类型断言可以支持你从存储在空接口中的值中取回原始类型。
类型断言用于检查接口中存储的值是否与特定类型匹配。没有类型断言时,你只能访问接口定义的方法,而不能访问原始值的字段或方法。

2.类型断言是如何工作的

如上所述,类型断言会检查接口内部的值是否与断言的类型匹配,并取回原始值。

Syntax:

value, ok := x.(OriginalType)

解析:
value:如果断言成功,存储原始类型值的变量。
ok:一个布尔值,指示断言是否成功(true)或失败(false)。

Example:

var x interface{}
x = "hello" // 将hello字符串赋值给空接口

v2, ok := x.(string) // 通过类型断言检查 x 是否包含字符串。
if ok {
fmt.Println("Assertion successful:", v2) // v2 包含字符串 "hello"
} else {
fmt.Println("Assertion failed")
}

在这个例子中,x.(string) 检查 x 是否保存了 string 类型。如果是,v2 将存储原始值,oktrue