How can I read private field in go struct instance

121 views
Skip to first unread message

杜沁园

unread,
Jun 3, 2019, 11:54:35 AM6/3/19
to golang-nuts
I recently write a program to recursively print all fields and value in a struct. Interface() is the most convinence way to get underlying value in go.
But it will panic when field is private.How can I access private field? 

For simple type, I can stil use Int(),Bool(),etc to read private field.   But if the field is a interface, I do not know how to access is concrete value without use Interface() method.


For example:

type Expr interface {
eval(v string) bool
}

type MyExpr struct {
Haha string
}

type Web struct {
Host string
epr Expr
}



How can I get Web.Epr Value by reflection without use Interface() method

Weiming Shi

unread,
Jun 3, 2019, 3:15:30 PM6/3/19
to 杜沁园, golang-nuts
Let us have some concrete code snippet for discussion:
https://play.golang.org/p/fdcEs3k9U8I

Is this what you would like to have?


--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/66703aa4-de59-4ae8-8407-928e7ebf95c5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Dan Kortschak

unread,
Jun 3, 2019, 8:19:55 PM6/3/19
to 杜沁园, golang-nuts
Sorry, missed the go- prefix in Dave's package.

github.com/davecgh/go-spew

On Tue, 2019-06-04 at 09:48 +0930, Dan Kortschak wrote:
> There are packages already available for this.
>
> github.com/kortschak/utter (for Go syntax-like printing)
> github.com/davecgh/spew (for less Go syntax-like printing)

Dan Kortschak

unread,
Jun 3, 2019, 8:41:23 PM6/3/19
to 杜沁园, golang-nuts
There are packages already available for this.

github.com/kortschak/utter (for Go syntax-like printing)
github.com/davecgh/spew (for less Go syntax-like printing)



On Mon, 2019-06-03 at 08:54 -0700, 杜沁园 wrote:

杜沁园

unread,
Jun 3, 2019, 10:44:12 PM6/3/19
to golang-nuts
go-spew is a really good library, I don not need to write it myself, Thanks

在 2019年6月4日星期二 UTC+8上午8:19:55,kortschak写道:

Dan Kortschak

unread,
Jun 3, 2019, 10:46:22 PM6/3/19
to 杜沁园, golang-nuts
The code in utter is essentially the same (I forked it from go-spew),
but the output can be used in Go code. Depending on what you want, both
are useful.
Reply all
Reply to author
Forward
0 new messages