#fmt prints unexported fields

8 messages · Page 1 of 1 (latest)

short bluff
#

Hi, I have a struct like this

package xd

type MyStruct struct {
    D int
    N int
    s int
}

func New() *MyStruct {
    return &MyStruct{
        D: 10,
        N: 50,
        s: 1,
    }
}

When I create an instance of this struct in main package I can't access the s field (is it called field?), because it's unexported and doesnt exist from my POV.
However if I print it from the main package I get

ii := xd.New()
fmt.Printf("%+v", ii)

// &{D:10 N:50 s:1}

how can fmt see the s field from main?

surreal oak
#

fmt uses reflect, reflect can read, but not write, unexported fields

short bluff
#

perfect tool for hackers I guess

#

can I somehow just bypass the fact that a field is unexported and access it anyways?

surreal oak
#

you can with reflect, but you shouldn't

#

and not "shouldn't" as in "that looks funky" but "shouldn't" as in "THAT'S A HORRIBLE IDEA", ya know? 😁

short bluff
#

xd

#

yea