In the first case, the interface contains a value of type S, which is
not writable. The value contained in the interface is not addressable.
So Unmarshal creates a new map and fills that. In the second case the
interface contains *S, which is writable, so unmarshal fills it in via
reflection.

On Wed, Apr 24, 2024 at 10:46 AM cpu...@gmail.com <cpui...@gmail.com> wrote:
>
> Every time I feel I've come to terms with how Go works I round a corner and 
> hit a wall, even after doing this for >5 years. Here's one.
>
> Consider this simple code (https://go.dev/play/p/bph5I80vc99):
>
> package main
>
> import (
> "encoding/json"
> "fmt"
> )
>
> type S struct {
> Foo int
> }
>
> func update(v any) {
> if err := json.Unmarshal([]byte(`{"Foo": 42}`), &v); err != nil {
> panic(err)
> }
> fmt.Printf("%v %T\n", v, v)
> }
>
> func main() {
> var val S
>
> // map[Foo:42] map[string]interface {}
> update(val)
>
> // &{42} *main.S
> update(&val)
> }
>
> Why would calling by value change the type of the value passed to map? I 
> would expect an interface with a dynamic type of main.S, but its 
> map[string]interface{}, or json.Unmarshal makes it so.
>
> Insights appreciated :)
>
> --
> You received this message because you are subscribed to the Google Groups 
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to golang-nuts+unsubscr...@googlegroups.com.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/golang-nuts/980466d2-1686-4b79-aec1-45b592db2caan%40googlegroups.com.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAMV2RqrUtoauyu8dHGrrVppY%3DeTVP7dCZkb%2Br_Ax696UuJy6dQ%40mail.gmail.com.

Reply via email to