Go Your First (Real) Program
With all the material we have covered so far, we can finally write our first real program. More precisely, we will write a program to convert a temperature from Celsius to Fahrenheit.
Define the Package name
The first statement in the Go programming starts with package name
. Here we are using package main
, which tells the compiler that the package should be compiled as an executable program instead of a shared library.
package main
Import the fmt Package
We need to import the fmt
package as we are using the fmt.Printf
function to print the output. Package fmt implements formatted I/O with functions analogous to C's printf
and scanf
.
import "fmt"
Define the constant
Later on, we will see how to ask the user for input but for now, we will hard-code the value of the temperature into a const
.
const celcius float64 = 21.0
Write the formula
The formula to convert a temperature from Celsius to Fahrenheit is:
const fahrenheit float64 = celcius*9/5 + 32
Since celcius
is a floating-point number, we do not need to write 9.0
or 5.0
in the formula.
Print the output
Finally, we can print the result:
fmt.Printf("%.2f°C is %.2f°F.\n", celcius, fahrenheit)
Your First (Real) Go Program Combining all the Code
All together, the program looks like this:
package main
import "fmt"
func main() {
const celcius float64 = 21.0
const fahrenheit float64 = celcius*9/5 + 32
fmt.Printf("%.2f°C is %.2f°F.\n", celcius, fahrenheit)
}
Output
21.00°C is 69.80°F.