1

First, the file structure is as follows:

 .
├── a
│   └── a.go
├── b
│   └── b.go
├── go.mod
└── main.go

a.go :

 package a

var Hello = "a"

func NewHello() {
    Hello = "aa"
}

b.go :

 package b

import (
    "fmt"
    "one/a"
)

var World = a.Hello

func NewWorld() {
    fmt.Printf(World)
}

main.go :

 package main

import (
    "one/a"
    "one/b"
)

func main() {
    a.NewHello()
    b.NewWorld()
}

The main problem here is in b.go , in my own main , when instantiating the program in ---7ac9003865341c75415a63052a00bbd3---, first instantiate a , and then I Instantiate b , then there is a sequence, then in b , the result I expect should be "aa" , in fact, the result I get is still is "a" .

I ignore here golang as a compiled language, when var is initialized, if there is an assignment, it will default to a known value when compiling, and the values of golang are all values The transfer method, and the modifications generated during the program operation will not modify the redefined variables.

So b.go modify to

 var World = &a.Hello

func NewWorld() {
    fmt.Printf(*World)
}

Get the pointer address of the original variable, and then use the pointer to get the data value of the original variable.

In fact, if you look at it in a single file, you won't make this mistake, but after putting the two variable definitions in two independent program files, I didn't think of this layer.


kumfo
6.7k 声望4.1k 粉丝

程序生存法则: