Monday, April 30, 2018

golang - compile and run a Go program

One very useful functionality which we would like to use is - Compilation and Execution in one command:

The syntax is:

go run <<fileName.go>>

To illustrate this point, let us consider the following example:

Suppose we have the file:

$ ls -l
total 4
-rw-rw-r-- 1 ubuntu ubuntu 82 Apr 30 12:00 hello.go


Let us check the contents of the file hello.go:

$ more hello.go 
package main

import "fmt"

func main() {
    fmt.Printf("hello, world 001\n")
}


Let us run it to see the output:

$ go run hello.go
hello, world 001


Now, let us make a small change in the program to print 002 in the output instead of 001:

$ vi hello.go 
$ more hello.go 
package main

import "fmt"

func main() {
    fmt.Printf("hello, world 002\n")
}


Let us compile and run again to review the output:

$ go run hello.go 
hello, world 002

We find that the output has changed. 






No comments:

Post a Comment