# Go 02 - Parse command line flags

A go program to convert temperatures from and to Fahrenheit using command line flags.

# Simple Program

A simple program that allows you to convert temperatures between Fahrenheit and Celsius using command line flags:

```go
package main

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

func fahrenheitToCelsius(fahrenheit float64) float64 {
    return (fahrenheit - 32) * 5/9
}

func celsiusToFahrenheit(celsius float64) float64 {
    return celsius*9/5 + 32
}

func main() {
    if len(os.Args) != 3 {
        fmt.Println("Usage: go run temp_converter.go <-f|-c> <temperature>")
        return
    }

    flag := os.Args[1]
    temp, err := strconv.ParseFloat(os.Args[2], 64)
    if err != nil {
        fmt.Println("Invalid input")
        return
    }

    if flag == "-f" {
        celsius := fahrenheitToCelsius(temp)
        fmt.Printf("%.2f°F is equivalent to %.2f°C", temp, celsius)
    } else if flag == "-c" {
        fahrenheit := celsiusToFahrenheit(temp)
        fmt.Printf("%.2f°C is equivalent to %.2f°F", temp, fahrenheit)
    } else {
        fmt.Println("Invalid flag. Use -f to convert from Fahrenheit to Celsius, or -c to convert from Celsius to Fahrenheit.")
    }
}
```

# Using the "flag" package

We can rewrite the program using the "flag" package and make it more compact.

```go
package main

import (
    "flag"
    "fmt"
)

func fahrenheitToCelsius(fahrenheit float64) float64 {
    return (fahrenheit - 32) * 5/9
}

func celsiusToFahrenheit(celsius float64) float64 {
    return celsius*9/5 + 32
}

func main() {
    fahrenheit := flag.Float64("f", 0, "temperature in Fahrenheit")
    celsius := flag.Float64("c", 0, "temperature in Celsius")
    flag.Parse()

    if *fahrenheit != 0 {
        c := fahrenheitToCelsius(*fahrenheit)
        fmt.Printf("%.2f°F is equivalent to %.2f°C", *fahrenheit, c)
    } else if *celsius != 0 {
        f := celsiusToFahrenheit(*celsius)
        fmt.Printf("%.2f°C is equivalent to %.2f°F", *celsius, f)
    } else {
        fmt.Println("Usage: go run temp_converter.go [-f temperature] [-c temperature]")
    }
}
```

# Run and Build

To use this program, save it to a file called `temp_converter.go`, and then run it using the `go run` command, followed by the `-f` or `-c` flag and the temperature that you want to convert:

```plaintext
$ go run temp_converter.go -f 100.0
100.00°F is equivalent to 37.78°C

$ go run temp_converter.go -c 37.5
37.50°C is equivalent to 99.50°F
```

You can also build the program into an executable and run it directly, like this:

```plaintext
$ go build temp_converter.go
$ ./temp_converter -f 100.0
100.00°F is equivalent to 37.78°C

$ ./temp_converter -c 37.5
37.50°C is equivalent to 99.50°F
```
