函数() 作为值编译错误

huangapple go评论105阅读模式
英文:

function() used as value compile error

问题

我正在尝试通过调整示例来学习Go的基础知识,教程位于这里:

http://tour.golang.org/#9


这是我写的一个小函数,它只是将每个字符都转换为大写。

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func capitalize(name string) {
  7. name = strings.ToTitle(name)
  8. return
  9. }
  10. func main() {
  11. test := "Sergio"
  12. fmt.Println(capitalize(test))
  13. }

我得到了这个异常:

>prog.go:15: capitalize(test) used as value

有什么明显的错误吗?

英文:

I'm trying to learn the basics of Go by tweaking examples as I go along the tutorial located here:

http://tour.golang.org/#9


Here's a small function I wrote that just turns ever character to all caps.

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func capitalize(name string) {
  7. name = strings.ToTitle(name)
  8. return
  9. }
  10. func main() {
  11. test := "Sergio"
  12. fmt.Println(capitalize(test))
  13. }

I'm getting this exception:

>prog.go:15: capitalize(test) used as value

Any glaring mistakes?

答案1

得分: 12

你忘记了为capitalize()函数指定返回类型:

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func capitalize(name string) string {
  7. return strings.ToTitle(name)
  8. }
  9. func main() {
  10. test := "Sergio"
  11. fmt.Println(capitalize(test))
  12. }

Playground


输出:

  1. SERGIO
英文:

You are missing the return type for capitalize():

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func capitalize(name string) string {
  7. return strings.ToTitle(name)
  8. }
  9. func main() {
  10. test := "Sergio"
  11. fmt.Println(capitalize(test))
  12. }

Playground


Output:

  1. SERGIO

huangapple
  • 本文由 发表于 2013年5月17日 04:24:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/16596805.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定