Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one use a variable name with the same name as a package in Go?

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)
}

The error I get is:

$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)
like image 909
Nate Avatar asked Oct 14 '11 18:10

Nate


People also ask

How do you use constants in Go?

In Go, const is a keyword introducing a name for a scalar value such as 2 or 3.14159 or "scrumptious" . Such values, named or otherwise, are called constants in Go. Constants can also be created by expressions built from constants, such as 2+3 or 2+3i or math. Pi/2 or ("go"+"pher") .

What does it mean by package name?

A package name is the full name of the package, which is defined via the NAME parameter in the pkginfo file. Because system administrators often use package names to determine whether or not a package needs to be installed, it is important to write clear, concise, and complete package names.


1 Answers

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"
)

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

pathpkg.Join(os.TempDir(), path)
like image 62
macbirdie Avatar answered Sep 27 '22 18:09

macbirdie