lundi 25 septembre 2023

Golang: Reflect returns different kind when same value depending on initialisation

Consider the following snippet of code:

// You can edit this code!
// Click here and start typing.
package main

import (
    "fmt"
    "reflect"
)

type MyStruct struct{}

func main() {
    m := make(map[string]any)
    m["key"] = make([]*MyStruct, 0)
    myStructs := m["key"]
    myStructsVal := reflect.ValueOf(&myStructs)
    fmt.Println(myStructsVal.Type().Kind())
    fmt.Println(myStructsVal.Type().Elem().Kind())

    nm := make(map[string][]*MyStruct)
    nm["key"] = make([]*MyStruct, 0)
    nmStructs := nm["key"]
    nmStructsVal := reflect.ValueOf(&nmStructs)
    fmt.Println(nmStructsVal.Type().Kind())
    fmt.Println(nmStructsVal.Type().Elem().Kind())
}

The following the output:

ptr
interface
ptr
slice

This means that reflect considers the first myStructsVal to be a pointer to an interface and the second nmStructsVal to be a pointer to slice. Am I wrong when I consider the treatment of both variables to be same by the reflect library? Am I missing something?

Any help or pointers would be appreciated. Thanks!

Here is the Go playground link.





Aucun commentaire:

Enregistrer un commentaire