我是一个新手程序员,对Go语言更是不熟悉。我写了一个小的Go程序,但是在编译时出现了未定义变量的错误。
以下是我的代码:
package main
import (
"fmt"
"io"
"os"
)
const file = "readfile.txt"
var s string
func lookup(string) (string, string, string) {
artist := s
album := s
year := s
return artist, album, year
}
func enterdisk() (string, string, string) {
var artist string
var album string
var year string
println("enter artist:")
fmt.Scanf("%s", &artist)
println("enter album:")
fmt.Scanf("%s", &album)
println("enter year:")
fmt.Scanf("%s", &year)
return artist, album, year
}
func main() {
println("enter UPC or [manual] to enter information manually:")
fmt.Scanf("%s", &s)
s := s
switch s {
case "manual\n": artist, album, year := enterdisk()
default: artist, album, year := lookup(s)
}
f,_ := os.OpenFile(file, os.O_APPEND|os.O_RDWR, 0666)
io.WriteString(f, (artist + ", \"" + album + "\" - " + year + "\n"))
f.Close()
println("wrote data to file")
}
以及错误信息:
catalog.go:49: undefined: artist
catalog.go:49: undefined: album
catalog.go:49: undefined: year
然而,这些变量直到代码运行时才会被定义。此外,“lookup”函数尚未编写,它只返回传递给它的内容。我知道lookup和enterdisk函数单独工作正常,但我试图测试switch语句。
我已经尝试在主函数中声明变量,但是我收到了以下错误:
catalog.go:49: artist declared and not used
catalog.go:49: album declared and not used
catalog.go:49: year declared and not used
p.s. 我已经阅读了 http://tip.goneat.org/doc/go_faq.html#unused_variables_and_imports ,我同意如果这只是语法问题,我仍然想要修复它,只是我不知道该怎么做!