go - Converting from []T1 to []T2 when T2 has the underlying type of T1 -


Two closely related questions:

Why do you allow change to [] T1 Do not give to [] T2 if T2 has the underlying type of T1

negative results

Example:

  Package main import ("fmt" Insecure ") type T1 struct {val int} / T2, the T1 type T2 type T2 type is the main main () {a: = [] T1 {T1 {12}} // one can not change type [] T1 [] T2 / B: = ([] T2) (A) // But some insecure So, we can do it. // So, why is not it allowed to go? And what could be the unexpected result? B: = * (* [] T2) (unsafe indicator (and a)) B [0 ] .Val = 42 fmt.Println (a [0] .Val) // 42}  

Playground:

< Strong> Example of use:

If T1 implements a fixed interface, then json .marshaler , and you have a Want to encode JSON differently, you create a new type T2 T1 with one of your code's json.marshaler .

It works fine while mastering single values, but when you get the [] T1 piece, you either have to copy it in [] T2 slice or a new Instead of turning on ST1 [] T1 with its own Martialson () method, it would be better to do a simple conversion rather than turn it on There may be runtime errors instead of compiling.

a non-continuous The value can be changed to type x if type X and T for example,

  package main import ("fmt") type T1 struct {Val int} Type T2 T1 Type ST1 [] T1 type ST2 ST1 func main () {a: = ST1 {T1 {42}} fmt.Println (a) // 42 // Type (type ST1) to type [ST2 b: = ST2 (a) fmt Println (b) // 42}  

Output:

  [[42}] [[42}]  

Comments

Popular posts from this blog

import - Python ImportError: No module named wmi -

Editing Python Class in Shell and SQLAlchemy -

c# - MySQL Parameterized Select Query joining tables issue -