Real-time Go struct memory layout visualization and optimization.
Using lazy.nvim
{
'Legion-ke/go-memory-visualizer.nvim',
ft = 'go',
config = function()
require('go-memory-visualizer').setup({
-- Optional: customize settings
default_architecture = 'amd64',
show_inline_annotations = true,
highlight_padding = true,
})
end
}Using packer.nvim
use {
'Legion-ke/go-memory-visualizer.nvim',
ft = 'go',
config = function()
require('go-memory-visualizer').setup()
end
}Using vim-plug
Plug 'Legion-ke/go-memory-visualizer.nvim'Then add to your init.lua:
require('go-memory-visualizer').setup()- Install the plugin using one of the methods above
- Open any
.gofile with struct definitions - See inline annotations automatically appear
- Use
:GoMemoryOptimizeto optimize the struct at cursor
| Command | Description |
|---|---|
:GoMemoryAnalyze |
Analyze current buffer |
:GoMemoryOptimize |
Optimize struct at cursor |
:GoMemoryToggleArch |
Cycle through amd64/arm64/386 |
:GoMemoryReport |
Show detailed report window |
:GoMemoryToggle |
Toggle plugin on/off |
require('go-memory-visualizer').setup({
-- Architecture for calculations (amd64, arm64, 386)
default_architecture = 'amd64',
-- Show memory info above each field
show_inline_annotations = true,
-- Highlight fields with padding waste
highlight_padding = true,
-- Minimum padding bytes to show warning
padding_warning_threshold = 8,
-- Warn about cache line crossings
show_cache_line_warnings = true,
-- Auto-update on buffer changes
auto_update = true,
})Add to your config:
vim.keymap.set('n', '<leader>ga', ':GoMemoryAnalyze<CR>', { desc = 'Analyze Go struct memory' })
vim.keymap.set('n', '<leader>go', ':GoMemoryOptimize<CR>', { desc = 'Optimize Go struct' })
vim.keymap.set('n', '<leader>gr', ':GoMemoryReport<CR>', { desc = 'Show memory report' })
vim.keymap.set('n', '<leader>gt', ':GoMemoryToggleArch<CR>', { desc = 'Toggle architecture' })Before optimization:
type User struct {
Active bool // 1 byte + 7 padding
ID uint64 // 8 bytes
Name string // 16 bytes
Age uint8 // 1 byte + 7 padding
Balance float64 // 8 bytes
}
// Total: 48 bytes | Padding: 14 bytes (29% waste)After running :GoMemoryOptimize:
type User struct {
ID uint64 // 8 bytes
Balance float64 // 8 bytes
Name string // 16 bytes
Active bool // 1 byte
Age uint8 // 1 byte + 6 final padding
}
// Total: 40 bytes | Padding: 6 bytes (15% waste)
// Saved 8 bytes (16.7% reduction)The plugin follows Go's memory alignment rules:
- Type Alignment: Each type has a natural alignment requirement
- Field Placement: Fields are placed at offsets aligned to their requirements
- Padding Insertion: Go adds padding bytes to satisfy alignment
- Struct Size: Rounded up to the largest field alignment
The optimizer reorders fields by:
- Sorting by alignment (descending)
- Then by size (descending)
- Recalculating layout with new ordering
- Neovim >= 0.8.0
- Go files (
.goextension)
MIT License - see LICENSE file