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:
package
main
import
(
"fmt"
;
"math"
)
func
distance
(
x1
,
y1
,
x2
,
y2
float64
)
float64
{
a
:=
x2
–
x1
b
:=
y2
–
y1
return
math
.
Sqrt
(
a
*
a
+
b
*
b
)
}
func
rectangleArea
(
x1
,
y1
,
x2
,
y2
float64
)
float64
{
l
:=
distance
(
x1
,
y1
,
x1
,
y2
)
w
:=
distance
(
x1
,
y1
,
x2
,
y1
)
return
l
*
w
}
func
circleArea
(
x
,
y
,
r
float64
)
float64
{
return
math
.
Pi
*
r
*
r
}
func
main
()
{
var
rx1
,
ry1
float64
=
0
,
0
var
rx2
,
ry2
float64
=
10
,
10
var
cx
,
cy
,
cr
float64
=
0
,
0
,
5
fmt
.
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:
type
Circle
struct
{
x
float64
y
float64
r
float64
}
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 ...
Get Introducing Go now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.