Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fmt: support printing reflect.Value directly #8965

Closed
rsc opened this issue Oct 20, 2014 · 4 comments
Closed

fmt: support printing reflect.Value directly #8965

rsc opened this issue Oct 20, 2014 · 4 comments
Milestone

Comments

@rsc
Copy link
Contributor

rsc commented Oct 20, 2014

A reflect.Value obtained from an unexported field does not support .Interface().
If you hold such a value there is no way to pass it to fmt.Print to get the underlying
value printed.
(The usual way is fmt.Print(v.Interface()).)

Rog asks for a way to print such a reflect.Value. He has cited two unsafe packages that
do this by modifying the Value to remove the 'obtained from unexported field' bit.

Two possibilities.

1) Add a new type, in either reflect or fmt, that fmt recognizes and prints. 
For example, type RawValue struct { V reflect.Value }.

2) Make fmt recognize reflect.Value and print the underlying value instead
of printing the reflect.Value struct as it does today.
@robpike
Copy link
Contributor

robpike commented Oct 20, 2014

Comment 1:

Ugh.

@rogpeppe
Copy link
Contributor

Comment 2:

I considered option 2, but I'm not sure it's a viable solution,
as %v will currently produce moderately useful output
when presented with a reflect.Value, because reflect.Value
implements String. People are probably relying on that.
Ugh, agreed. FWIW I would not have agreed to include this hack
in production code, but it's very useful in tests. On reflection,
I should probably clone/reimplement that part of fmt, but the above
RawValue fix would be preferable.

@bradfitz bradfitz modified the milestone: Go1.5 Dec 16, 2014
@robpike
Copy link
Contributor

robpike commented Apr 9, 2015

I don't understand the issue. This program prints 3.

package main

import (
"fmt"
"reflect"
)

type t struct { a int }

func main() {
var x = t{3}
fmt.Println(reflect.ValueOf(x.a).Interface())
}

@robpike
Copy link
Contributor

robpike commented Apr 9, 2015

This shows the problem:

package main

import (
"fmt"
"reflect"
)

type t struct{ a int }

func main() {
var x = t{3}
fmt.Println(reflect.ValueOf(x).Field(0).Interface())
}

@rsc rsc removed accepted labels Apr 14, 2015
@golang golang locked and limited conversation to collaborators Jun 25, 2016
@rsc rsc unassigned robpike Jun 23, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants