File tree Expand file tree Collapse file tree 3 files changed +59
-0
lines changed
internal/examples/basic/structs Expand file tree Collapse file tree 3 files changed +59
-0
lines changed Original file line number Diff line number Diff line change @@ -24,4 +24,5 @@ func (r *register) Regist(m mappings.ExampleMapping) {
2424 m ["struct_deep_equal" ] = StructDeepEqual
2525 m ["struct_blank_identifier" ] = BlankIdentifier
2626 m ["struct_same_method" ] = SameMethodOnEachTypes
27+ m ["struct_memory_padding" ] = MemoryPadding
2728}
Original file line number Diff line number Diff line change 1+ package structs
2+
3+ import (
4+ "unsafe"
5+
6+ "github.com/devlights/gomy/output"
7+ "github.com/devlights/try-golang/internal/examples/basic/structs/types"
8+ )
9+
10+ // MemoryPadding は、構造体メンバーの定義順によってGoランタイムがメモリ上にパディングを挿入することを確認するサンプルです.
11+ func MemoryPadding () error {
12+ var (
13+ notGood = types.MemoryPadding {}
14+ good = types.NoMemoryPadding {}
15+ )
16+
17+ output .Stdoutl ("[Padding 発生]" , unsafe .Sizeof (notGood ))
18+ output .Stdoutl ("" , notGood .Layout ())
19+ output .Stdoutl ("[Padding なし]" , unsafe .Sizeof (good ))
20+ output .Stdoutl ("" , good .Layout ())
21+
22+ return nil
23+ }
Original file line number Diff line number Diff line change 1+ package types
2+
3+ // MemoryPadding は、メンバー定義順によってメモリのパディングが発生する構造体です.
4+ type MemoryPadding struct {
5+ Flag1 bool
6+ ShortVal int16
7+ Flag2 bool
8+ FloatVal float32
9+ }
10+
11+ // NoMemoryPadding は、メンバー定義順を考慮してメモリのパティングが発生しないようにしている構造体です.
12+ type NoMemoryPadding struct {
13+ FloatVal float32
14+ ShortVal int16
15+ Flag1 bool
16+ Flag2 bool
17+ }
18+
19+ func (MemoryPadding ) Layout () string {
20+ return `
21+ | Flag1 | | ShortVal | Flag2 | | FloatVal |
22+ -----------------------------------------------------------------------------
23+ | bool (1) | padding (1) | int16 (2) | bool (1) | padding (3) | float32 (4) |
24+ | 4 | 4 | 4 |
25+ `
26+ }
27+
28+ func (NoMemoryPadding ) Layout () string {
29+ return `
30+ | FloatVal | ShortVal | Flag1 | Flag2 |
31+ -------------------------------------------------
32+ | float32 (4) | int16 (2) | bool (1) | bool (1) |
33+ | 4 | 4 |
34+ `
35+ }
You can’t perform that action at this time.
0 commit comments