Compile and Execute a GO program

  • We will describe how to compile and execute a GO program. A simple program (program1.go) is shown below.
  • Move your mouse to the code block and click on the Copy button. The code will be copied to your clipboard and you can then paste it in your own editor window or IDE (Integrated Development Environment) and save it under the name program1.go.
/* program1.go */
package main

import ( "fmt" ; "math" )

func curve(x, A, B float64) float64 {
   y := A * x * math.Exp(-1.1*x)
   if x > B {
      y = y + B*(x-B)*math.Exp(-1.1*(x-B))
   }
   return y
}

func main() {
   A := 5.0
   B := 4.0
   for i := 0; i < 100; i++ {
      x := float64(i) / 10.0
      fmt.Println(x, curve(x, A, B))
   }
}
  • On Linux and MacOS terminals, as well as on the Windows command or cmd terminals, this can be compiled and run using the command
    • go run program1.go
  • You can also create an executable file using the command:
    • go build program1.go
  • This will create an executable binary called
    • program1 on Linux or MacOS
    • program1.exe on Windows
  • The executable can be run as follows:
    • ./program1 on Linux or MacOS
    • program1 on Windows
  • If you are using an IDE, you will have to use whatever commands are available for compiling and executing.

Here is part of the output you would get:

$ go run program1.go 
0 0
0.1 0.4479170676482641
0.2 0.8025187979624784
0.3 1.0783856001478895
0.4 1.2880728421662826
0.5 1.4423745259512166
0.6 1.5505540034750975
0.7 1.6205457390892983
0.8 1.6591316467263253
0.9 1.6720951095992054
1 1.6643554184903975
1.1 1.6400850368643802
...