Skip to content

Instantly share code, notes, and snippets.

@mashiro
Last active August 28, 2017 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mashiro/cdaf05ab032c99fcf3b8413a24665b80 to your computer and use it in GitHub Desktop.
Save mashiro/cdaf05ab032c99fcf3b8413a24665b80 to your computer and use it in GitHub Desktop.
フィールドと同じ名前の getter を定義したい場合の回避策
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