Golang array type conversion

Recent encounter when writing code conversion type, sometimes to separate variable casts no problem, but if forced conversion of complex variables (such as arrays) will be a problem.
Question 1: You can use [] T1 is converted to [] T2 it? T1 and T2 are the same type of bottom.
The answer is no, a look at an example:
type Tl int
type T2 int
var T1 Tl
var X = T2 (T1) the OK //
var ST1 [] Tl
var SX = ([] T2) (ST1) the OK // the NOT
in Go , closely related to the type and method, because each type has named a (possibly empty) set of methods. The general rule is, you can change the name of the type you want to convert (which may change its methods set), but can not change the name of the complex type elements (and a set of methods). Go requires you to explicitly type conversion. That golang the composite type refers to? Complex type comprising pointers, arrays, slices, the Map, structure. So array types cast is problematic. But through the array, the conversion for each element, i.e., to achieve the desired thought [] Tl is converted to [] T2
Question 2: may be [] T cast [] interface {} it?
The answer: no. Can traverse an array, to convert a single element, but directly to the whole array will do the conversion error
language specification does not allow this, because these two different types of representations in memory. The necessary elements are copied to the target slice. This example converts a portion int to interface {} part:
T: = [] int {. 1, 2,. 3,. 4}
S: = the make ([] interface {}, len (T))
for I, V: = range t {
S [I] = V
}
Referring Base:
https://golang.org/doc/faq#convert_slice_with_same_underlying_type

Published 156 original articles · won praise 132 · Views 250,000 +

Guess you like

Origin blog.csdn.net/u013276277/article/details/104109573