Skip to Main Content
Think Julia
book

Think Julia

by Ben Lauwens, Allen B. Downey
April 2019
Beginner content levelBeginner
295 pages
5h 48m
English
O'Reilly Media, Inc.
Content preview from Think Julia

Chapter 15. Structs and Objects

At this point you know how to use functions to organize code and built-in types to organize data. The next step is to learn how to build your own types to organize both code and data. This is a big topic; it will take a few chapters to get there.

Composite Types

We have used many of Julia’s built-in types; now we are going to define a new type. As an example, we will create a type called Point that represents a point in two-dimensional space.

In mathematical notation, points are often written in parentheses with a comma separating the coordinates. For example, 0 , 0 represents the origin, and x , y represents the point x units to the right and y units up from the origin.

There are several ways we might represent points in Julia:

  • We could store the coordinates separately in two variables, x and y.

  • We could store the coordinates as elements in an array or tuple.

  • We could create a new type to represent points as objects.

Creating a new type is more complicated than the other options, but it has advantages that will be apparent soon.

A programmer-defined composite type is also called a struct. The struct definition for a point looks like this:

struct Point
    x
    y
end

The header indicates that the new struct is called Point. The body defines the attributes or fields of the struct. The Point struct has two fields: x and y.

A struct is like a factory for creating objects. To create a point, you call Point as if it were a function having ...

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.
Start your free trial

You might also like

Practical Julia

Practical Julia

Lee Phillips
Getting Clojure

Getting Clojure

Russ Olsen
Learning Go

Learning Go

Jon Bodner

Publisher Resources

ISBN: 9781492045021Errata PageSupplemental Content