有没有办法像Go一样使用Rust的频道?我找不到任何东西.
对于那些不熟悉Go中的select语句的人(来自文档):
"select"语句选择一组可能的发送或接收操作中的哪一个将继续.它看起来类似于"switch"语句,但所有情况都涉及通信操作.具有RecvStmt的情况可以将RecvExpr的结果分配给一个或两个变量,这些变量可以使用短变量声明来声明.RecvExpr必须是(可能是带括号的)接收操作.最多只能有一个默认情况,它可能出现在案例列表中的任何位置.
执行"select"语句分几步进行:
- 对于语句中的所有情况,接收操作的通道操作数以及发送语句的通道和右侧表达式在输入"select"语句后按源顺序精确计算一次.结果是一组要接收或发送的通道,以及要发送的相应值.无论选择哪种(如果有的话)通信操作进行,评估中的任何副作用都将发生.尚未评估具有短变量声明或赋值的RecvStmt左侧的表达式.
- 如果一个或多个通信可以继续,则可以通过统一的伪随机选择来选择可以继续的单个通信.否则,如果存在默认情况,则选择该情况.如果没有默认情况,则"select"语句将阻塞,直到至少一个通信可以继续.
- 除非所选择的情况是默认情况,否则执行相应的通信操作.
- 如果所选案例是具有短变量声明或赋值的RecvStmt,则评估左侧表达式并分配接收值(或多个值).
- 执行所选案例的语句列表.
由于nil通道上的通信永远不会进行,因此只选择nil通道并且永远不会出现默认情况.
例如,我怎么能在Rust中写这个?
func search(ctx context.Context, result chan IResult, q string) error {
// googleSearch and bingSearch will return IResult interface channel
google := googleSearch(q)
bing := bingSearch(q)
t := time.After(time.Second)
for {
select {
// at any point if caller cancel the operation we return
case <- ctx.Done():
return nil
case r, ok := <- google:
if !ok { // check if channel is closed
google = nil
if …Run Code Online (Sandbox Code Playgroud) 假设我有一个名为的接口Hello:
type Hello interface {
Hi() string
}
Run Code Online (Sandbox Code Playgroud)
我想编写一个获取Hello和任何接口的函数,n并在Hello实现n接口的情况下执行某些操作,例如:
type Person interface {
Name() int
}
type Animal interface {
Leg() int
}
type hello struct{}
func (h hello) Hi() string {
return "hello!"
}
func (h hello) Leg() int {
return 4
}
func worker() {
h := hello{}
// Doesn't match
check(h,(Person)(nil))
// Matches
check(h,(Animal)(nil))
}
func check(h Hello, n interface{}) {
// of course this doesn't work, …Run Code Online (Sandbox Code Playgroud)