Last active
August 28, 2017 10:23
-
-
Save mashiro/cdaf05ab032c99fcf3b8413a24665b80 to your computer and use it in GitHub Desktop.
フィールドと同じ名前の getter を定義したい場合の回避策
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
) | |
type ( | |
User interface { | |
Name() string | |
} | |
userImpl struct { | |
Name string `json:"name"` | |
} | |
user struct { | |
impl userImpl | |
} | |
) | |
func (u user) MarshalJSON() ([]byte, error) { | |
return json.Marshal(&u.impl) | |
} | |
func (u *user) UnmarshalJSON(data []byte) error { | |
return json.Unmarshal(data, &u.impl) | |
} | |
func (u *user) Name() string { | |
return u.impl.Name | |
} | |
func main() { | |
s := `{"name": "yui"}` | |
u := user{} | |
err := json.Unmarshal([]byte(s), &u) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(u.Name()) // yui | |
bytes, err := json.Marshal(u) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(string(bytes)) // {"name":"yui"} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment