Frontier Software

Assignment

Introducing assignment into our programming language leads us into a thicket of difficult conceptual issues. — Structure and Interpretation of Computer Programs

Fahrenheit/Celsius Table

package main

import (
	"fmt"
)

const lower = -40
const upper = 300
const step = 20

func main() {
	var fahr, celsius int
	fahr = lower
	for fahr <= upper {
		celsius = 5 * (fahr - 32) / 9
		fmt.Printf("%d\t%d\n", fahr, celsius)
		fahr = fahr + step
	}
}

As in C, all variables must be declared before they are used, usually at the beginning of the function before any executable statements.

The differences from the original C example in K&R:

  1. In go, type declarations come at the end instead of the beginning.
  2. There is only a for loop which can be made to act just like C’s while.
  3. I put ; at the end of each statement which go fmt fahrenheit_celsius.go removed.

Symbolic constants

#define	LOWER	0	/* lower limit of table */
#define	UPPER	300	/* upper limit */
#define	STEP	20	/* step size */

Go’s const is fairly identical to C’s #define. Not sure if Go has an all upercase convention, since that would export constants even if I don’t want to.

:= vs =

Instead of declaring fahr and celsius as typed variables C-style, Go allows variables to be introduced anywhere (as in Bash, JavaScript, Python…) using the := operator which is used in Hugo. Later reassignment of these variables requires the = operator.

package main

import (
	"fmt"
)

const lower = -40
const upper = 300
const step = 20

func main() {
	fahr := lower
	for fahr <= upper {
		celsius := 5 * (fahr - 32) / 9
		fmt.Printf("%d\t%d\n", fahr, celsius)
		fahr = fahr + step
	}
}

The short variable declaration operator := can only be used within functions, not if variables and constants are defined outside of functions:

Type inference

A snag with the := short variable declaration operator is it infers int, so if I want the table to be float, I have to declare it:

package main

import (
	"fmt"
)

const lower = -40
const upper = 300
const step = 20

func main() {
	var fahr, celsius float64
	fahr = lower
	for fahr <= upper {
		celsius = (5.0 / 9.0) * (fahr - 32.0)
		fmt.Printf("%f\t%f\n", fahr, celsius)
		fahr = fahr + step
	}
}

Using Go’s for in a more conventional way:

package main

import (
	"fmt"
)

const lower = -40
const upper = 300
const step = 20

func main() {
	var fahr, celsius float64
	for fahr = lower; fahr <= upper; fahr = fahr + step {
		celsius = (5.0 / 9.0) * (fahr - 32.0)
		fmt.Printf("%f\t%f\n", fahr, celsius)
	}
}