【已解决】go语言运行出错:# command-line-arguments .\EmulateLoginBaidu.go:17: line declared and not used

【问题】

折腾:

【记录】go语言中把代码移至独立的函数中:搞懂go语言中函数的写法

期间,用如下代码:

package main

import (
    "fmt"
    "runtime"
    "path"
    "strings"
)

// GetCurFilename
// Get current file name, without suffix
func GetCurFilename() string {
    _, fulleFilename, line, _ := runtime.Caller(0)
    //fmt.Println(fulleFilename)
    //fmt.Println(line)
    var filenameWithSuffix string
    filenameWithSuffix = path.Base(fulleFilename)
    //fmt.Println("filenameWithSuffix=", filenameWithSuffix)
    var fileSuffix string
    fileSuffix = path.Ext(filenameWithSuffix)
    //fmt.Println("fileSuffix=", fileSuffix)
    
    //filenameWithSuffix = "EmulateLoginBaidu"
    //fileSuffix = ".go"
    //filenameWithSuffix = "EmulateLoginBaidu.go.go.go"
    //fileSuffix = ".go"
    //filenameWithSuffix = "EmulateLoginBaidu.go.txt"
    //fileSuffix = ".go"
    var filenameOnly string
    filenameOnly = strings.TrimSuffix(filenameWithSuffix, fileSuffix)
    //fmt.Println("filenameOnly=", filenameOnly)
    
	return filenameOnly
}

func main() {
    fmt.Printf("this is EmulateLoginBaidu.go\n")
    
    var filenameOnly string
    filenameOnly = GetCurFilename()
    fmt.Println("filenameOnly=", filenameOnly)
}

运行,结果出错:

D:\tmp\tmp_dev_root\go\src\github.com\user\EmulateLoginBaidu>go run EmulateLoginBaidu.go

# command-line-arguments

.\EmulateLoginBaidu.go:17: line declared and not used

如图:

line declared and not used

即:

line declared and not used

【解决过程】

1.然后后来才注意到,原来是:

    _, fulleFilename, line, _ := runtime.Caller(0)
    //fmt.Println(fulleFilename)
    //fmt.Println(line)

中的返回值line,后面没有用到,所以有此警告。

2.所以,去参考:

_, fulleFilename, line, _ := runtime.Caller(0)

的写法,推测是:

下划线_,表示忽略此返回值,所以去改为:

func GetCurFilename() string {
    _, fulleFilename, _, _ := runtime.Caller(0)
    //fmt.Println(fulleFilename)

试试结果:

然后程序就正常执行了,没有了此警告了:

D:\tmp\tmp_dev_root\go\src\github.com\user\EmulateLoginBaidu>go run EmulateLoginBaidu.go
this is EmulateLoginBaidu.go
filenameOnly= EmulateLoginBaidu

如图:

go code run ok no not used warning

 

【总结】

go代码中,如果有变量(赋值了)但是后期没有引用,就会出现:

line declared and not used

的警告(而导致程序无法编译过,无法运行)



发表评论

电子邮件地址不会被公开。 必填项已用*标注

无觅相关文章插件,快速提升流量