Skip to content

Commit b1abb5c

Browse files
authored
Merge pull request #672 from devlights:add-reflection-example
Add reflect example
2 parents dac6ad6 + 22c5bf7 commit b1abb5c

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed

examples/basic/reflects/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,8 @@
44

55
|file|example name|note|
66
|----|------------|----|
7+
|typeof.go|reflect\_typeof|reflect.TypeOf() のサンプルです|
8+
|valueof.go|reflect\_valueof||
9+
|value.go|reflect\_value||
710
|selectcase.go|reflect\_selectcase|reflect.SelectCase のサンプルです|
811
|find\_type.go|reflect\_find\_type|実行時に型を求めるやり方についてのサンプルです|

examples/basic/reflects/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ func NewRegister() mapping.Register {
1313

1414
// Regist -- 登録します.
1515
func (r *register) Regist(m mapping.ExampleMapping) {
16+
m["reflect_typeof"] = TypeOf
1617
m["reflect_selectcase"] = SelectCase
1718
m["reflect_find_type"] = FindType
1819
}

examples/basic/reflects/typeof.go

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package reflects
2+
3+
import (
4+
"reflect"
5+
6+
"github.com/devlights/gomy/output"
7+
)
8+
9+
// TypeOf -- reflect.TypeOf() のサンプルです.
10+
//
11+
// # REFERENCES
12+
// - https://pkg.go.dev/reflect@go1.21.1
13+
// - https://go.dev/blog/laws-of-reflection
14+
func TypeOf() error {
15+
//
16+
// Goでリフレクションを利用する場合は reflect パッケージを使う。
17+
// 使い方としてはC#などの他の言語と同じイメージ。
18+
//
19+
// - 型を取得するには reflect.TypeOf() を使用する
20+
// - 値を取得するには reflect.ValueOf() を使用する
21+
//
22+
23+
type (
24+
MyInt int
25+
MySt struct {
26+
s string
27+
i int64
28+
ui uint64
29+
f float64
30+
ch chan string
31+
sli []int
32+
m map[int]int
33+
}
34+
)
35+
36+
var (
37+
i = 0
38+
mi = MyInt(0)
39+
st = MySt{"helloworld", int64(100), uint64(100), float64(100.0), make(chan string), []int{1}, map[int]int{1: 2}}
40+
)
41+
42+
var (
43+
ti = reflect.TypeOf(i)
44+
tmi = reflect.TypeOf(mi)
45+
tst = reflect.TypeOf(st)
46+
)
47+
48+
output.Stdoutf("[ti ]", "%T\t%v\t%dbytes\n", ti, ti, ti.Size())
49+
output.Stdoutf("[tmi]", "%T\t%v\t%dbytes\n", tmi, tmi, tmi.Size())
50+
output.Stdoutf("[tst]", "%T\t%v\t%dbytes\n", tst, tst, tst.Size())
51+
52+
for idx := 0; idx < tst.NumField(); idx++ {
53+
f := tst.Field(idx)
54+
output.Stdoutf(" >>>", "\t%T:\t%s\t%dbytes\n", f, f.Type.Name(), f.Type.Size())
55+
56+
// スライス、マップ、チャネルは f.Type.Name() では表示されない
57+
}
58+
59+
return nil
60+
}

0 commit comments

Comments
 (0)