新手问题 不同方式导引代码导致一个变量有两个地址

gogoa · 2017年03月20日 · 最后由 toyijiu 回复于 2017年03月20日 · 436 次阅读

代码结构是这样的:

  • test
    • main.go
    • p1
      • test.go
    • p2
      • test.go

main.go的代码是

package main
import (
    _ "./p1"
    "./p2"
)
func main() {
    p2.Print()
}

p1.test.go的代码是

package p1
import (
    "test/p2"
)
func init() {
    p2.Print()
}

p2.test.go的代码是

package p2

import (
    "fmt"
)

var a int

func Print() {
    fmt.Printf("%p\n", &a)
}

输出

0x1127ac0
0x1127938

如果修改 p1.test 的导入方式为

import (
    "../p2"
)

就正常

截图

更多原创文章干货分享,请关注公众号
  • 加微信实战群请加微信(注明:实战群):gocnio

非常不建议用相对地址引入包

1.本地 package import 的时候可以用相对路径吗?我试了下编译不过,识别不了路径。而且在网上查了下本地包都说不能用相对路径。绝对路径肯定是没问题的,两个地址打印都一样。 2.初始化顺序是递归 main 包里 import 的 package,每个 package 的初始化顺序是 const->var->init(),所以按道理讲两个打印都是调 p2 的 Print,肯定都是打印 a 的地址

找了一下相对路径的说明: Relative import paths

An import path beginning with ./ or ../ is called a relative path. The toolchain supports relative import paths as a shortcut in two ways.

First, a relative path can be used as a shorthand on the command line. If you are working in the directory containing the code imported as "unicode" and want to run the tests for "unicode/utf8", you can type "go test ./utf8" instead of needing to specify the full path. Similarly, in the reverse situation, "go test .." will test "unicode" from the "unicode/utf8" directory. Relative patterns are also allowed, like "go test ./..." to test all subdirectories. See 'go help packages' for details on the pattern syntax.

Second, if you are compiling a Go program not in a work space, you can use a relative path in an import statement in that program to refer to nearby code also not in a work space. This makes it easy to experiment with small multipackage programs outside of the usual work spaces, but such programs cannot be installed with "go install" (there is no work space in which to install them), so they are rebuilt from scratch each time they are built. To avoid ambiguity, Go programs cannot use relative import paths within a work space.

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册