Chapter 7. Structs and Interfaces
Although it would be possible for us to write programs only using Go’s built-in data types, at some point it would become quite tedious. Consider a program that interacts with shapes:
packagemainimport("fmt";"math")funcdistance(x1,y1,x2,y2float64)float64{a:=x2–x1b:=y2–y1returnmath.Sqrt(a*a+b*b)}funcrectangleArea(x1,y1,x2,y2float64)float64{l:=distance(x1,y1,x1,y2)w:=distance(x1,y1,x2,y1)returnl*w}funccircleArea(x,y,rfloat64)float64{returnmath.Pi*r*r}funcmain(){varrx1,ry1float64=0,0varrx2,ry2float64=10,10varcx,cy,crfloat64=0,0,5fmt.Println(rectangleArea(rx1,ry1,rx2,ry2))fmt.Println(circleArea(cx,cy,cr))}
This program finds the area of a rectangle and a circle. Keeping track of all the coordinates makes it difficult to see what the program is doing and will likely lead to mistakes.
Structs
An easy way to make this program better is to use a struct. A struct is a type that contains named fields. For example, we could represent a circle like this:
typeCirclestruct{xfloat64yfloat64rfloat64}
The type keyword introduces a new type. It’s followed by the name of the type (Circle), the keyword struct to indicate that we are defining a struct type, and a list of fields inside of curly braces.
Fields are like a set of grouped variables. Each field has a name and a type and is stored adjacent to the other fields in the struct. Like with functions, we ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access