为什么reflect.ValueOf不能在golang中使用Println打印int的真实值 [英] Why reflect.ValueOf can not print out true value of int using Println in golang
问题描述
func main(){
var val interface {} = 11
fmt.Println(reflect.ValueOf(val))
} //打印出来:< int Value>
但是在传递字符串之后,比如Hello给val,它会打印出字符串本身。
我注意到struct结构有一个方法
$ b $ $ p $ func(v Value)String()string
它表示如果v'type不是一个字符串,它将返回一个形式为[T value]的字符串,其中T是v的类型,但是,为什么不返回[int 11]之类的东西,我也知道应该向ValueOf()附加一个Int()函数来获取val的实际值,但我不明白值结构,和字符串函数和Println函数
我不是Go作者或任何东西,但我认为设计是Go的三个属性的产物:
- 一般情况下,Getters不会出现
Get
< a href =http://golang.org/doc/effective_go.html#Getters =nofollow>来源 - fmt包使用
String
方法(如果可用)。 源 - 隐式满足接口
第一种导致像 Int
, Float
, Bool
, String
等等。如果调用错误的类型,除 String
外。这是因为fmt会使用 String
,并且很可能有许多其他包获取该值的字符串表示形式,并且只有字符串值才可打印,这当然是不合理的。可以说,应该有另一种返回底层字符串而不是 String
的方法,但这意味着api的一致性会降低,所以他们选择了两个恶意中较小的一个。
func main() {
var val interface{} = 11
fmt.Println(reflect.ValueOf(val))
}//print out : <int Value>
But after I pass string,like "Hello" to val,it will print out the string itself. I notice that value struct has a method
func (v Value) String() string
It says that if v'type is not a string,it returns a string of the form "[T value]" where T is v's type,but,why not returning something like [int 11],I also know that I should append an Int() function to ValueOf() to get the actual value of val,but I do not understand the internal relationship between value struct,and String function and the Println function
I'm not a Go author or anything, but I think the design is a product of three properties of Go:
- Getters commonly leave off
Get
source - The fmt package uses a
String
method if it is available. source - Interfaces are satisfied implicitly
The first leads to the methods like Int
, Float
, Bool
, String
etc. All of these methods will panic if called on a value of the wrong type, except String
. This is because String
would be used by fmt, and likely many other packages to get a string representation of the value, and it is surely unreasonable for only string values to be printable. Arguably there should be another method which returns the underlying string instead of String
, but that would mean less consistency in the api, so they chose the lesser of two evils.
这篇关于为什么reflect.ValueOf不能在golang中使用Println打印int的真实值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!