如何在Go中使用与包相同名称的变量名? [英] How does one use a variable name with the same name as a package in Go?

查看:53
本文介绍了如何在Go中使用与包相同名称的变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件或目录的通用变量名称是路径".不幸的是,这也是Go中包的名称.此外,在DoIt中将路径更改为参数名称,如何获取此代码进行编译?

A common variable name for files or directories is "path". Unfortunately that is also the name of a package in Go. Besides, changing path as a argument name in DoIt, how do I get this code to compile?

package main

import (
    "path"
    "os"
)

func main() {
    DoIt("file.txt")
}

func DoIt(path string) {
    path.Join(os.TempDir(), path)
}

我得到的错误是:

$6g pathvar.go 
pathvar.go:4: imported and not used: path
pathvar.go:13: path.Join undefined (type string has no field or method Join)

推荐答案

路径字符串正在隐藏导入的 path .您可以将导入的程序包的别名设置为例如通过将 import 中的行"path" 更改为 pathpkg"path" 中的pathpkg,这样代码的开头就像这样

The path string is shadowing the imported path. What you can do is set imported package's alias to e.g. pathpkg by changing the line "path" in import into pathpkg "path", so the start of your code goes like this

package main

import (
    pathpkg "path"
    "os"
)

当然,您必须将 DoIt 代码更改为:

Of course then you have to change the DoIt code into:

pathpkg.Join(os.TempDir(), path)

这篇关于如何在Go中使用与包相同名称的变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆