Now that we have the basics down, let apply them to something more real, and perhaps the previous concepts covered will become more clear. When I learn a new programming language I generally start with trying to create a program to solve the Tricky Triangle. If you have ever been to Cracker Barrel, you know what it is. It goes by some other names too, but it is usually a triangular piece of wood with holes in it with enough golf tees to fill all but one whole. You play a checkers like jump rules where you remove the peg you jumped over You keep going until you have no available moves left. The goal is to only have one peg left. The code for the lesson is here.
[Read More]Beginning Programming Lesson 07
Packages and Modules
In previous lesson we put all of out code in one file and one package, main
. However, aside from very small projects, this won’t scale very well, and does make your code very reusable apart from copying and pasting. We have already seen the usefulness of packages through using the fmt
and errors
packages. So let’s look at how to create our own. You can find the code for today’s lesson here. There is more than one file this time!
Beginning Programming Lesson 06
Recursion and Error Handling
When I was in college my professor explained recursion as “Pretend you already have a function that does what you need to do.” The problem with that explanation is, it only makes sense after you understand recursion. I think we can do better here. While we are at it, let’s look at error handling too. You can find the code for today’s lesson here.
package main
import (
"fmt"
"log"
)
type MinInputError struct {
}
func (e *MinInputError) Error() string {
return "invalid input, number must be greater than 0"
}
type MaxInputError struct {
}
func (e *MaxInputError) Error() string {
return "invalid input, number must be less than 100"
}
func Factorial(n int) int {
if n == 1 {
return n
}
return n * Factorial(n-1)
}
func Factorial2(n int) (int, error) {
if n < 0 {
return 0, &MinInputError{}
}
if n > 100 {
return 0, &MaxInputError{}
}
ret := n
for i := n - 1; i > 0; i-- {
ret = ret * i
}
return ret, nil
}
func main() {
fmt.Println(Factorial(10))
fmt.Println(Factorial2(10))
fmt.Println(Factorial2(-10))
f, err := Factorial2(-13)
if err != nil {
log.Print(err)
} else {
fmt.Println(f)
}
f, err = Factorial2(100000000000)
if _, ok := err.(*MaxInputError); ok {
fmt.Println("Do something special")
} else {
fmt.Println(f)
}
}
Recursion
If you want to understand recursion, check out my tutorial on recursion. (:-p) (Sorry I couldn’t help myself). Anyway, a recursive function/method is one that calls itself in its definition. It’s probably best to look at an example. Let’s create a function that calculates the factorial of a number. In case you don’t recall:
[Read More]Beginning Programming Lesson 05
Inheritance, Interfaces, and Type Assertion
We created complex data types (structs/classes), but what if we wanted to create another struct
that expands upon another? Or you wanted to create a number of different structs that play by a certain set of rules. The example code for today can be found here.
package main
import (
"fmt"
"math"
)
type Polygon interface {
Shape() string
Perimeter() float64
Area() float64
}
type Rectangle struct {
Length float64
Height float64
}
func (r Rectangle) Perimeter() float64 {
return 2*r.Height + 2*r.Length
}
func (r Rectangle) Area() float64 {
return r.Height * r.Length
}
func (r Rectangle) Shape() string {
return "rectangle"
}
func (r Rectangle) String() string {
return fmt.Sprintf("Shape: %s, Dimensions: %fx%f, Perimeter: %f, Area: %f", r.Shape(), r.Length, r.Height, r.Perimeter(), r.Area())
}
type ColoredRectangle struct {
Rectangle
Color string
}
func (r ColoredRectangle) String() string {
return fmt.Sprintf("Shape: %s, Dimensions: %fx%f, Perimeter: %f, Area: %f, Color: %s", r.Shape(), r.Length, r.Height, r.Perimeter(), r.Area(), r.Color)
}
type Triangle struct {
Sides [3]float64
}
func (t Triangle) Perimeter() float64 {
return t.Sides[0] + t.Sides[1] + t.Sides[2]
}
func (t Triangle) Area() float64 {
p := t.Perimeter() / 2
return math.Sqrt(p * (p - t.Sides[0]) * (p - t.Sides[1]) * (p - t.Sides[2]))
}
func (t Triangle) Shape() string {
return "triangle"
}
func (t Triangle) String() string {
return fmt.Sprintf("Shape: %s, Dimensions: %fx%fx%f, Perimeter: %f, Area: %f", t.Shape(), t.Sides[0], t.Sides[1], t.Sides[2], t.Perimeter(), t.Area())
}
func printSlice(s []interface{}) {
for i, v := range s {
fmt.Printf("%d - %v\n", i, v)
}
}
func main() {
rect := Rectangle{Length: 5, Height: 4}
tri := Triangle{Sides: [3]float64{4, 5, 6}}
fmt.Println(rect)
fmt.Println(tri)
var polys []Polygon
polys = append(polys, rect)
polys = append(polys, tri)
var cr ColoredRectangle
cr.Height = 7
cr.Length = 8
cr.Color = "red"
polys = append(polys, cr)
fmt.Println(polys)
for _, p := range polys {
fmt.Println(p)
}
fmt.Printf("Shape 1 type: %s\n", polys[0].Shape())
random := []interface{}{1, "blue", rect, tri}
printSlice(random)
if _, ok := random[1].(Polygon); !ok {
fmt.Println("Not a polygon")
}
fmt.Println(random[2].(Polygon).Shape())
}
Interfaces
An interface in general provides a way of communication between two or more parties. A GUI (Graphical User Interface) provides a means communication between a computer and a human. In the case of Golang and many other programming languages, an interface is a definition of how a struct
must behave in order to work with other portions of code that expect them to follow the definition. In our last lesson we created a struct
polygon
. It had a method to calculate the perimeter. What if we wanted to have it calculate area? Well, the area calculation varies from polygon to polygon. While there are a number of ways we could deal with this, let’s see how we could use interfaces to help.
Beginning Programming Lesson 04
Control Structures and Array-Like Things
We now know how to create and use variables, structs, and functions. But thus far, all the examples have been fairly linear. What if we want do things only when certain criteria are met? Or what if we want to do the same thing many times in a row? What if we want want store a bunch of a rectangles from the previous lesson? This is where control structures, arrays and slices come in handy. You can download this lessons code here.
[Read More]Beginning Programming Lesson 03
Complex Data Types (Structs/Classes)
In the last installment of this series we learned about variables, and covered some simple variable types. Now we are going to learn about complex data types. In short, they store more than a single data point of information. For example, what if we wanted to have a variable that stored information about a rectangle? There is more than one bit of information to describe it. At minimum you would probably want to store its width and length. Depending on the language you use, there are different terms for the data types that can hold such information. The main two are classes and structs (short for structures). Some languages use both, but in the case of Golang it uses structs. You can download the example code here, or see below:
[Read More]Beginning Programming Lesson 02
Variables, Functions, Importing, Pointers, and Scope.
Now that you have your setup ready to go, we can start writing some code! Note that we are just touching the surface of the topics covered in this lesson, but the sooner you start writing code, the easier it will become to understand the topics better. Plus you are more likely to continue, if you feel like you are accomplishing something, rather than learning more and more theory.
You can download the file here. I suggest creating a folder to store all the files for this and future examples. Also create a sub-folder for each individual lesson, since they all will be named main.go
. Open it up in VS Code, and open a terminal. Make sure you are in the correct folder/directory by using the pwd
command. Use the cd
command to change directories if needed. Then go ahead and run it by executing:
Beginning Programming Lesson 01
Introduction and the Tools
When I was about 12 years old, my aunt gave us an old computer. Without going into all the details, I broke it, and all that it would then let you do is write programs in BASIC. It came with a book explaining how to do various things with the language. So having nothing better to do, I worked through it and taught myself how to code, and eventually went to college to learn how to do it better. Now I make a living writing software. I have good news for you. For most people and what they want to do with software development, you don’t need to spend tons of money. You can find pretty much everything you need on the Internet. With the tutorials that follow I hope to make it even easier for you. Basic understanding on how to use a computer, browse the Web, and some middle school math is required, but that’s pretty much it. We won’t go into exhaustive detail on every topic covered in this series, but it should be enough to get you going. So, let’s get on with what you will need.
[Read More]