Golang Code

Passing Arguments into your Application

· 168 words · 1 minute read #application #args #arguments #bool #cmd #command #flags #parse #runtime

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.

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.

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!