如何更改程序包的执行时间?

huangapple go评论150阅读模式
英文:

How to change when packages are excecuted

问题

我有一个Go语言的包A,看起来像这样:

package A

var Something int

func Do_something() {
    Something = 100
}

在包A中的do_something函数被main.go中调用:

package main

import "example.com/this_project/A"

func main() {
    A.Do_something()
}

这个工作得很好,但现在我添加了包B。

package B

import (
    "example.com/this_project/A"
    "fmt"
    "strconv"
)

_ = do_something_else()

func do_something_else() {
    fmt.Println("%s is the value of something", strconv.Itoa(A.Something))
}

func Some_other_function() {
    do_whatever()
}

Some_other_function也会在main.go中被调用:

package main

import (
    "example.com/this_project/A"
    "example.com/this_project/B"
)

func main() {
    A.Do_something()
    B.Some_other_function()
}

当我运行这个程序时,我期望它输出:

100

但实际上,它输出:

0

我认为这意味着包B在main.go之前运行,所以我尝试使用time.sleep,但它只会导致整个项目停止。任何建议将不胜感激。

英文:

I have a package A in Go that looks like

package A

var Something int

func Do_something() {

    Something = 100

}

where do_something in package A is called in main.go

package main

import "example.com/this_project/A"

func main() {

    A.Do_something()

}

That works well, but now I add package B.

package B

import (
    "example.com/this_project/A"
    "fmt"
    "strconv"
)

_ = do_something_else()

func do_something_else() {

    fmt.Println("%s is the value of something", strconv.Itoa(A.Something))        

}

func Some_other_function() {

    do_whatever()

}

Some_other_function will also get called in main.go

package main

import "example.com/this_project/A"
import "example.com/this_project/B"

func main() {

    A.Do_something()
    B.Some_other_function()

}

When I run this program, I expect it to output

100

But instead, it outputs

0

I think this means that package B is running before main.go, so I tried using time.sleep, but it just caused the entire project to stop. Any suggestions will be appreciated.

答案1

得分: 3

所有全局变量在main开始运行之前都会被初始化。因此,这行代码:

_ = do_something_else()

会在main开始之前运行,这将打印变量的当前值,此时为0。

英文:

All global variables are initialized before main starts running. Because of that, this line:

_ = do_something_else()

will run before main starts, which will print the current value of the variable, which is 0 at that point.

huangapple
  • 本文由 发表于 2021年11月5日 23:24:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/69855585.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定