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.

    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.