dshtze500055 2018-09-10 16:08
浏览 127

go build和go run之间的函数调用差异

I'm new to Golang and I'm trying out a few examples as part of my learning. I have 2 Go source files - hello.go and consts.go in my example. consts.go contains some constants which are used by the functions defined in hello.go. When I build both the source files like so: go build consts.go hello.go and run the output ./hello the function arrayDemo() is not called at all.

However, when I just run the file hello.go using go run hello.go, the function arrayDemo() is called.

What is the difference in both the approaches that's causing the function not to be called when building?

Here's the code for hello.go:

package main

import (
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    fmt.Printf("Speed is %f
", computeSpeed(54.3, 3.4))
    fmt.Printf("%d
", arrayDemo())
}

func arrayDemo() int32 {
    fmt.Println("in arrayDemo")
    return 5
}

Code for consts.go:

package main

// Speed speed of a vehicle
type Speed float32

func computeSpeed(dist float32, t float32) Speed {
    return Speed(dist / t)
}
  • 写回答

1条回答 默认 最新

  • dongxia5394 2018-09-11 13:42
    关注

    go run works because go run works based on file names, but go build works based on package names.

    also

    go help build says:
    

    When compiling multiple packages or a single non-main package, build compiles the packages but discards the resulting object, serving only as a check that the packages can be built.

    to my understanding this means you can not have multiple files in the main package and then get working executable by using go build

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据