Search code examples
go

Embedding in Go with pointer or with value


I can embed in golang with pointer and value. By pointer

type Bitmap struct{
    data [4][4]bool
}

type Renderer struct{
    *Bitmap
    on uint8
    off uint8
}

By value

type Bitmap struct{
    data [4][4]bool
}

type Renderer struct{
    Bitmap 
    on uint8
    off uint8
}

What is more prefer by pointer or value?


Solution

  • It depends. There are several possibilities here.

    • If Renderer is passed around by value and the methods you need on Bitmap are defined on *Bitmap, then you'll need to embed *Bitmap.
    • If Renderer is passed around as a pointer, then you can embed Bitmap as a value without any problem (pointer methods will still be accessible in this case).
    • If Bitmap has a constructor function that returns a pointer, and the zero value of Bitmap isn't usable, you'll want to embed *Bitmap, as you don't want to encourage by-value copying of the Bitmap value.
    • If all the Bitmap methods are value methods, then you definitely want to embed by value.

    In the specific case you have here, I'd probably embed by value, as the type is small - it gives you locality of access and less memory allocations.