【背景】
折腾:
期间,已经搞定:
此处是,把相关的代码,整理到独立的函数中。
【折腾过程】
1.关于go语言的函数写法,之前已经通过:
中的:
“点击在线文档中的函数,可以看到完整的代码实现”
而可以参考官网的api的实现了。
2.其中就可以参考对应的函数:
http://golang.org/pkg/path/#Ext
->
http://golang.org/src/pkg/path/path.go?s=4113:4141#L153
看到代码:
// Ext returns the file name extension used by path. // The extension is the suffix beginning at the final dot // in the final slash-separated element of path; // it is empty if there is no dot. func Ext(path string) string { for i := len(path) - 1; i >= 0 && path[i] != '/'; i-- { if path[i] == '.' { return path[i:] } } return "" }
参考一下,去写自己的函数。
3.去试试代码:
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
再去参考:
【已解决】go语言编译运行出错:imported and not used: "log"
去解决此问题。
即,代码改为:
func GetCurFilename() string { _, fulleFilename, _, _ := runtime.Caller(0) //fmt.Println(fulleFilename)
即可解决此处问题。
4.然后可以正常运行,输出为:
D:\tmp\tmp_dev_root\go\src\github.com\user\EmulateLoginBaidu>go run EmulateLoginBaidu.go this is EmulateLoginBaidu.go filenameOnly= EmulateLoginBaidu
如图:
【总结】
此处,是可以通过:
当前文件内,直接定义对应的函数,然后调用即可。
其写法,大概为:
package main import ( "fmt" "runtime" "path" "strings" ) // GetCurFilename // Get current file name, without suffix func GetCurFilename() string { _, fulleFilename, _, _ := runtime.Caller(0) var filenameWithSuffix string filenameWithSuffix = path.Base(fulleFilename) var fileSuffix string fileSuffix = path.Ext(filenameWithSuffix) var filenameOnly string filenameOnly = strings.TrimSuffix(filenameWithSuffix, fileSuffix) return filenameOnly } func main() { var filenameOnly string filenameOnly = GetCurFilename() fmt.Println("filenameOnly=", filenameOnly) }
即可。
转载请注明:在路上 » 【记录】go语言中把代码移至独立的函数中:搞懂go语言中函数的写法