Skip to content

Commit c92b2a2

Browse files
committed
Add struct_memory_padding.go
1 parent 7a37e25 commit c92b2a2

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

internal/examples/basic/structs/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff 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
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
}

0 commit comments

Comments
 (0)