更新时间:2023-11-02 19:41:22
我不是Go作者或任何东西,但我认为设计是Go的三个属性的产物:
Get
来源 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:
Get
source String
method if it is available. source
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.