Skip to Content
Learning Functional Programming in Go
book

Learning Functional Programming in Go

by Lex Sheehan
November 2017
Intermediate to advanced
670 pages
17h 35m
English
Packt Publishing
Content preview from Learning Functional Programming in Go

Open/closed principle

Software should be open for extension but closed for modification. Embedding fields in a struct allows us to extend one type with another. The object (CarWithSpare) that embedded the other (Car) has access to its fields and methods. The CarWithSpare object can call Car methods, but cannot modify the Car object's methods. Therefore, Go's types, while being open for extension, are closed for modification. Let's look at an example:

package carimport "fmt"type Car struct {   Make string   Model string}func (c Car) Tires() int { return 4 }func (c Car) PrintInfo() {   fmt.Printf("%v has %d tires\n", c, c.Tires())}

We defined our Car type and two methods, Tires and PrintInfo. Next, we'll define our CarWithSpare type and embed the ...

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

Learning Functional Programming

Learning Functional Programming

Jack Widman

Publisher Resources

ISBN: 9781787281394Supplemental Content