This is the 8th day of my participation in Gwen Challenge

Can I convert []T to []interface{}?

The answer is: not directly. This is because the two types do not behave the same in memory according to the language specification. In order to convert, the slice elements must be converted individually. Here is an example of converting an int array to an interface array.

t := []int{1.2.3.4}
s := make([]interface{}, len(t))
for i, v := range t {
    s[i] = v
}
Copy the code
Specification standardCopy the code

If T1 and T2 are of the same type, can we convert []T1 to []T2?

The last line in the following example will not compile.

type T1 int
type T2 int
var t1 T1
var x = T2(t1) // OK
var st1 []T1
var sx = ([]T2)(st1) // NOT OK
Copy the code

In the Go language, types are tightly bound to some method, that is, all types have some method bound. As a general rule, you can change a type (possibly by changing the set of methods it binds together), but you can’t change a compound type (containing a series of elements) (PS: thus map is also not directly convertible).

Go requires you to explicitly cast (PS: for collections, you need to cast one by one)

Why does Go not have variant types?

Variant types are better known as algebraic types. It allows values to be of multiple types, but only specified ones. A common example in programming is an error, either a network error, a security error, or an application error, which allows programmers to identify the source of the error by distinguishing between error types. Another example is a syntax tree, where each node can be of a different type: declaration, statement, assignment, and so on.

We considered adding variant types, but decided not to use them after discussion because their use with interfaces can be confusing. Consider: What if elements in variant Types are interfaces to themselves?

In addition, some significant features of Variant types are already available in Go. For example, in the error example above, we can use the interface, with its value to store error, type to distinguish the type of error. The syntax tree example also works, although it may not be elegant.

Don't discriminate, overlap VCopy the code