jl-ecs/request.go

52 lines
1022 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package ecs
// 结果
type Result[T any] struct {
Val T
Err error
}
type EmptyType struct{}
// 新建一个OK空结果
func NewOkEmptyResult() Result[EmptyType] {
return Result[EmptyType]{Val: struct{}{}, Err: nil}
}
// 新建一个OK结果
func NewOkResult[T any](val T) Result[T] {
return Result[T]{Val: val, Err: nil}
}
func NewResult[T any](val T, err error) Result[T] {
return Result[T]{Val: val, Err: err}
}
// 新建一个错误结果
func NewErrResult(err error) Result[EmptyType] {
return Result[EmptyType]{Val: struct{}{}, Err: err}
}
// 请求世界执行给定函数
func Request[T any](w World, handler func() Result[T]) chan Result[T] {
future := make(chan Result[T])
err := w.Execute(func() {
result := handler()
select {
// 即使外面不接收也不会卡停World运行
case future <- result:
default:
}
})
// 世界执行错误直接响应错误
if err != nil {
go func() {
select {
case future <- Result[T]{Err: err}:
default:
}
}()
}
return future
}