【问题标题】:How to solve "too many arguments to return" issue如何解决“返回的参数太多”问题
【发布时间】:2014-08-22 20:40:05
【问题描述】:

在我正在编写的打印函数中,我试图根据 switch 语句的结果返回一个值;但是,我得到的错误是返回的参数太多。

如果这个问题有一个简单的答案,请原谅我,但是一个函数有多少个参数并且它只能返回一件事难道不应该吗?或者它是否需要为每个参数返回一个东西。

这是我的代码。我在返回行上收到错误(返回的参数太多)。如何修复它以使其返回 switch 语句中设置的字符串?

package bay

func Print(DATA []TD, include string, exclude []string, str string) {
    result := NBC(DATA, include, exclude, str)
    var sentAnal string
    switch result {
    case 1:
        sentAnal = "Strongly Negative"
    case 2:
        sentAnal = "Very Negative"
    case 3:
        sentAnal = "Negative"
    case 4:
        sentAnal = "Little Negative"
    case 5:
        sentAnal = "Neurtral"
    case 6:
        sentAnal = "Little Positive"
    case 7:
        sentAnal = "Positive"
    case 8:
        sentAnal = "More Positive"
    case 9:
        sentAnal = "Very Positive"
    case 10:
        sentAnal = "Strongly Positive"
    default:
        sentAnal = "Unknown"
    }
    return sentAnal
}

【问题讨论】:

  • 你在 Neurtal 行有错字应该是“Neutral” :)
  • 应该是“中性”

标签: go


【解决方案1】:

你需要指定输入参数后你会返回什么,这不是python。

这个:

func Print(DATA []TD, include string, exclude []string, str string) {

应该是:

func Print(DATA []TD, include string, exclude []string, str string) string {

推荐阅读:

甚至所有effective go

【讨论】:

  • 你是对的。当我写这篇文章时,我认为我并没有完全切换到 golang 的思维定势。谢谢。
  • 我特别喜欢“……这不是 python”。附录
【解决方案2】:

您指定的方法的签名不包含返回值

func Print(DATA []TD, include string, exclude []string, str string) {

如果要返回一个字符串需要加上返回值的类型

func Print(DATA []TD, include string, exclude []string, str string) string {

请记住,在 GO 中您可以返回多个值

func Print(DATA []TD, include string, exclude []string, str string) (string, string) {

您甚至可以为返回值命名并在代码中引用它

func Print(DATA []TD, include string, exclude []string, str string) (sentAnal string) {

【讨论】:

    【解决方案3】:

    如果您提到返回类型为string,那么您应该在返回语句中使用fmt.Sprintf,而不是fmt.Printf

    因为fmt.Printf的retun类型是(n int, err error)fmt.Sprintf的返回类型是string

    它不回答 OP 问题,但可能对其他人有帮助。

    【讨论】:

    • 这确实很有帮助。谢谢。
    猜你喜欢
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    相关资源
    最近更新 更多