不能使用函数(func()类型)作为参数中的类型
package mainimport (
"log"
"strings"
"asl.com/asl"
)
/*
Trivial service to demonstrate chaining service together
Message starts in originator, travels through a couple formatters, and then gets back to originator
*/
type MessageTest struct {
Body string `json:"body"`
}
var s *asl.Service
func main() {
var (
err error
cid string
)
//var m MessageDelivery
var g asl.MessageHandler
g = UpperCaseHandler
// UpperCaser := asl.NewService("UpperCaser", "", false)
UpperCaser := asl.NewService("UpperCaser")
if err = UpperCaser.ConsumeFunc("asl-service-uc", []string{"asl-service-uc"},func() interface{} {
return ""
},g); err != nil {
log.Fatalf("Error starting consumer: %v", err)
}
// Repeater := asl.NewService("Repeater", "", false)
Repeater := asl.NewService("Repeater")
if err = Repeater.ConsumeFunc("asl-service-repeat", []string{"asl-service-repeat"}, func() interface{} {
return ""
}, RepeatHandler); err != nil {
//if err = Repeater.ConsumeFunc("asl-service-repeat", []string{"asl-service-repeat"}, mg asl.MessageGenerator, mh asl.MessageHandler); err != nil {
log.Fatalf("Error starting consumer: %v", err)
}
// originator := asl.NewService("Originator", "", false)
originator := asl.NewService("Originator")
deliveryChan := make(chan asl.MessageDelivery)
m := asl.MessagePublishing{
Message: MessageTest{"this is a test"},
RoutingKeys: []string{"asl-service-uc", "asl-service-repeat"},
}
if cid, err = originator.RPCPublish(m, deliveryChan); err != nil {
log.Fatalf("Failed to publish: %v", err)
}
message := <-deliveryChan
log.Printf("Originator Got: %+v", message.Message)
originator.RemoveQueue(cid)
UpperCaser.Wait()
}
func UpperCaseHandler(md asl.MessageDelivery) {
s.Reply(MessageTest{strings.ToUpper(md.Message.(string))}, md.Delivery)
}
func RepeatHandler(md asl.MessageDelivery) {
s.Reply(MessageTest{strings.Repeat(md.Message.(string), 5)}, md.Delivery)
}
package asl
Error
./chains.go:26:10:不能在作业中使用UpperCaseHandler(typefunc(asl.MessageDelivery))作为asl.MessageHandler类型./chains.go:37:86:无法使用RepeatHandler(类型func(asl.MessageDelivery))与Repeater.ConsumeFunc的参数中的asl.MessageHandler类型相同
type MessageDelivery struct { Delivery amqp.Delivery
Message interface{}
Error error
Context *Context
}
type MessageGenerator func() interface{}
type MessageHandler func(MessageDelivery) (interface{}, error)
我试图运行代码,哪里出了问题,我该如何正确地将函数作为参数传递给另一个函数。该函数返回接口和错误。虽然函数以MessageDelivery
Struct作为参数,但是函数签名是相同的。
回答:
您正确地将该函数作为参数传递,但是它们与预期的签名不匹配。将功能更改为:
func UpperCaseHandler(md busboy.MessageDelivery) (interface{}, error} { s.Reply(MessageTest{strings.ToUpper(md.Message.(string))}, md.Delivery)
return nil, nil
}
func RepeatHandler(md busboy.MessageDelivery) (interface{}, error} {
s.Reply(MessageTest{strings.Repeat(md.Message.(string), 5)}, md.Delivery)
return nil, nil
}
以上是 不能使用函数(func()类型)作为参数中的类型 的全部内容, 来源链接: utcz.com/qa/426240.html