Skip to Content
The Go Programming Language
book

The Go Programming Language

by Alan A. A. Donovan, Brian W. Kernighan
October 2015
Beginner to intermediate
400 pages
14h 44m
English
Addison-Wesley Professional
Content preview from The Go Programming Language

6.3 Composing Types by Struct Embedding

Consider the type ColoredPoint:

gopl.io/ch6/coloredpoint
import "image/color"

type Point struct{ X, Y float64 }

type ColoredPoint struct {
    Point
    Color color.RGBA
}

We could have defined ColoredPoint as a struct of three fields, but instead we embedded a Point to provide the X and Y fields. As we saw in Section 4.4.3, embedding lets us take a syntactic shortcut to defining a ColoredPoint that contains all the fields of Point, plus some more. If we want, we can select the fields of ColoredPoint that were contributed by the embedded Point without mentioning Point:

var cp ColoredPoint
cp.X = 1
fmt.Println(cp.Point.X) // "1"
cp.Point.Y = 2
fmt.Println(cp.Y) // "2"

A similar ...

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

The Rust Programming Language, 2nd Edition

The Rust Programming Language, 2nd Edition

Steve Klabnik, Carol Nichols
Programming Rust, 2nd Edition

Programming Rust, 2nd Edition

Jim Blandy, Jason Orendorff, Leonora F. S. Tindall
Grokking Algorithms

Grokking Algorithms

Aditya Bhargava

Publisher Resources

ISBN: 9780134190570Purchase book