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

代码结构是这样的:



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

就正常


截图

已邀请:

傅小黑

赞同来自:

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

toyijiu - 编程爱好者

赞同来自:

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.

要回复问题请先登录注册