Passing Arguments into your Application

· 198 words · 1 minute read

Passing arguments in your application can be especially useful when you’re creating tools which can do different things, or the same thing in a different way. In go, you can do with by declaring your arguments as flags. In our example we’re using an argument to determine whether we should run task A or task B. Once you’ve declared your flags, you have to parse them at runtime to populate the variables and then you can use it like any other variable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main

import (
    "flag"
    "fmt"
)

// Param 1: Argument name, called like ./args --taska
// Param 2: Sets the default state, false would mean task B runs by default
// Param 3: Is the description of that command, shown if you call ./args --help
var toRunTaskA = flag.Bool("taska", false, "Whether to run task A or taskB")

func main() {

    flag.Parse()

    if *toRunTaskA {
        runTaskA()
    } else {
        runTaskB()
    }
}

func runTaskA() {
    fmt.Println("Runing Task A...")
}

func runTaskB() {
    fmt.Println("Running Task B...")
}

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!