Go中如何传递SQS.new()实例?函数签名该如何定义?
Got it, let's tackle your two SQS client questions with clear examples and explanations:
1. What's the correct parameter type for the SQS client?
The issue with your function signatures (func(svc *SQS) and func(svc SQS)) is that you're missing the package prefix for the SQS type.
When you call sqs.New(sess), it returns a *sqs.SQS pointer type—where sqs is the name of the AWS SDK package you imported. Go requires you to explicitly reference the package for types from external dependencies, so your function needs to accept *sqs.SQS as the parameter type, not just *SQS or SQS.
2. How to pass the SQS client instance to a function?
Once you've got the correct type sorted, passing the client is straightforward: just pass the svc variable you created directly to your function that accepts *sqs.SQS.
Here's a complete working example:
import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sqs" ) func main() { // Create your session and SQS client sess, err := session.NewSession(&aws.Config{ Region: aws.String("us-east-1"), // Replace with your AWS region }) if err != nil { panic(err) // Handle error properly in production code } svc := sqs.New(sess) // Pass the client to your custom function queueURL := "https://sqs.us-east-1.amazonaws.com/123456789012/your-queue" if err := sendTestMessage(svc, queueURL); err != nil { panic(err) } } // Correct function signature: accepts *sqs.SQS func sendTestMessage(svc *sqs.SQS, queueURL string) error { input := &sqs.SendMessageInput{ MessageBody: aws.String("Hello from the SQS client!"), QueueUrl: aws.String(queueURL), } _, err := svc.SendMessage(input) return err }
Quick note on package aliases (optional)
If you want to shorten the package name for readability, you can use an alias when importing:
import s "github.com/aws/aws-sdk-go/service/sqs"
Then your function signature becomes func sendTestMessage(svc *s.SQS, queueURL string) error—but stick with the full sqs. prefix if you want to avoid confusion.
内容的提问来源于stack exchange,提问作者lostintranslation

