Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit7bbe8d4

Browse files
committed
Document pointer pattern for path existence checking
Add documentation and tests showing how to use pointer types withDecodePath to check if a path exists rather than relying on zero values.This follows standard Go patterns for optional values.
1 parentdd4a944 commit7bbe8d4

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

‎reader_test.go‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,16 @@ func TestDecodePath(t *testing.T) {
367367
varneuint
368368
require.NoError(t,result.DecodePath(&ne,"does-not-exist",1))
369369
assert.Equal(t,uint(0),ne)
370+
371+
// Test pointer pattern for path existence checking
372+
varexistingStringPtr*string
373+
require.NoError(t,result.DecodePath(&existingStringPtr,"utf8_string"))
374+
assert.NotNil(t,existingStringPtr,"existing path should decode to non-nil pointer")
375+
assert.Equal(t,"unicode! ☯ - ♫",*existingStringPtr)
376+
377+
varnonExistentStringPtr*string
378+
require.NoError(t,result.DecodePath(&nonExistentStringPtr,"does-not-exist"))
379+
assert.Nil(t,nonExistentStringPtr,"non-existent path should decode to nil pointer")
370380
}
371381

372382
typeTestInterfaceinterface {

‎result.go‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,20 @@ func (r Result) Decode(v any) error {
5959
//
6060
// If the path is empty, the entire data structure is decoded into v.
6161
//
62+
// To check if a path exists (rather than relying on zero values), decode
63+
// into a pointer and check if it remains nil:
64+
//
65+
//var city *string
66+
//err := result.DecodePath(&city, "city", "names", "en")
67+
//if err != nil {
68+
//// Handle error
69+
//}
70+
//if city == nil {
71+
//// Path not found
72+
//} else {
73+
//// Path exists, city contains the value
74+
//}
75+
//
6276
// Returns an error if:
6377
// - the path is invalid
6478
// - the data cannot be decoded into the type of v
@@ -69,7 +83,7 @@ func (r Result) Decode(v any) error {
6983
// Example usage:
7084
//
7185
//var city string
72-
//err := result.DecodePath(&city, "location", "city", "names", "en")
86+
//err := result.DecodePath(&city, "city", "names", "en")
7387
//
7488
//var geonameID int
7589
//err := result.DecodePath(&geonameID, "subdivisions", 0, "geoname_id")

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp