This is a creation in Article, where the information may have evolved or changed.
In the function's pass-through value, interface{} can be passed arbitrary arguments, just like the Java object.
Here's the first time I've taken it for granted. * * ERROR code
package mainfunc main() { Any(2) Any("666")}func Any(v interface{}) { v1:=int(v) println(v1) }
I just want it to be compiled, because the error code above does not have any syntax errors, only 666 to say, the following is the compiler error prompt:
Cannot convert V (type interface {}) to type Int:need type assertion
The correct code will ensure that the program does not make any mistakes.
package mainfunc main() { Any(2) Any("666")}func Any(v interface{}) { if v2, ok := v.(string);ok{ println(v2) }else if v3,ok2:=v.(int);ok2{ println(v3) }}
The output is as follows
2666
Have to marvel at the rigor of go. Java writes a similar code and then it's gone.
Invisible I sprayed a lot of Java, but it is 20 years ago the language, older than me, some problems are really no way, now based on the JVM Kotlin, if I did not give up Android, I think I now the main working language is it.
Explain why Golang some cases, strong turn can, a little case, strong turn can not:
In fact, stack overflow a foreign great God said very well,
Exact words + wild translation
The reason why cannot convert an interface typed value is these rules in the referenced specs parts:
Conversions is expressions of the form T (x) where T was a type and x is an expression, that can being converted to type T.
A non-constant value X can is converted to type T in any of these cases:
- X is assignable to T.
- X ' s type and T have identical underlying types.
- X ' s type and T is unnamed pointer types and their pointer base types have identical underlying types.
- X's type and T is both integer or floating point types.
- X ' s type and T are both complex types.
- X is an integer or a slice of bytes or runes and T is a string type.
- X is a string and T is a slice of bytes or runes.
But
iAreaId := int(val)
Is isn't any of the cases 1.-7.
Address: About interface{} as a parameter
The wild translations are as follows:
I am too lazy to turn over ....